A custom directive was created in AngulerJS 1. It has in isolate scope, and is data-aware (gets data from server API). Its definition looks like this:
var dirJobView = function ($location, serviceData) {
return {
restrict: 'A',
templateUrl: '/app/views/Jobs/Item.html',
scope: {
itemid: "@"
},
controller: ['$scope', function ($scope) {
scope = $scope;
// does not work - data is not displayed in view:
serviceData.get('jobs', scope.itemid).then(function (data) {
scope.dataJobView = data;
});
}],
link: function (scope, elem, attrs, ctrl) {
}
};
}
The above is not working - the data is loaded, but the view does not display it. To be more exact, it only displays it if I force "Clear Cache and Hard Reload" in the browser.
However, it works perfeclty well if I move the service call to the link function like so:
var dirJobView = function ($location, serviceData) {
return {
restrict: 'A',
templateUrl: '/app/views/Jobs/Item.html',
scope: {
itemid: "@"
},
controller: ['$scope', function ($scope) {
scope = $scope;
}],
link: function (scope, elem, attrs, ctrl) {
// Moved from controller, now works
serviceData.get('jobs', scope.itemid).then(function (data) {
scope.dataJobView = data;
});
}
};
}
From what I understand, the link function is intended for manipulating the DOM, and the controller is meant to invoking the services and defining the behaviour. The call to service data should be placed in the controller, shouldn't it?
Why is the above works the way it does?
scope.$apply()
in the controller after thescope.dataJobView = data
and check if anything changes.