I am getting started with AngularJS and have a noob problem that I am not sure how to resolve. I am modifying a value outside of angular (I have put it in the .run section only for demonstration purposes), and then attempting to run $apply so that Angular will notice that the scope needs to be updated.
However, in the following code, the {{currentState}} value gets set to "Initial value" and does not ever update to "Second value".
What is the correct approach to get the value to update?
angular.module("exampleApp", [])
.run(function(userNotificationService) {
userNotificationService.setStatus("Initial value");
setTimeout(function() {
userNotificationService.setStatus("Second value");
}, 1000);
})
.factory('userNotificationService', function($rootScope) {
var currentState = 'Unknown state'; // this should never be displayed
return {
setStatus: function(state) {
$rootScope.$apply(function() {
currentState = state;
});
},
getStatus: function() {
return currentState;
}
};
}).directive('currentState', function(userNotificationService) {
return {
restrict: 'AE',
scope: false, // set to false so that directive scope is used for transcluded expressions
link: function(scope) {
scope.currentState = userNotificationService.getStatus();
}
};
}).controller("defaultCtrl", function ($scope) {
// does nothing
});
And the html is the following:
<body ng-controller="defaultCtrl">
<div current-state>
current state: {{ currentState }}
</div>
</body>