Reputation: 2643
Are you able to bind a directive to a getter property on a service using AngularJs?
I have a directive that is trying to watch a property on a service, it gets updated once on app start. Then it never updates, even when the watched property updates.
Here is my directive:
authorization.directive("authorization", ["$rootScope", "authenticationService", "authorizationService", function ($rootScope, authenticationService, authorizationService) {
return {
restrict: "A",
link: function (scope, element, attrs) {
var prevDisp = element.css("display");
function update(user) {
if (!authorizationService.isAuthorized(attrs.authorization, user)) { element.css("display", "none"); }
else { element.css("display", prevDisp); }
}
scope.$watch(authenticationService.user, function () { update(authenticationService.user); });
}
};
} ]);
Here is a cutdown version of my service:
App.factory("authenticationService", function ($http, $location) {
var _user = { email: null, ...... };
return {
get user() { return _user; }, //This is the property I am trying to bind too
login: function () { do stuff },
logout: function () { do other things }
}
});
Upvotes: 3
Views: 1941
Reputation: 2402
$watch
evalates functions or expressions, and in case of expressiones, there are evaluated against the current scope. If you are going to watch a variable, make sure it is attached to the scope first:
scope.user = authenticationService.user
scope.$watch('user', function (user, old) { update(user); });
Upvotes: -1
Reputation: 16435
You either watch an actual function (that's a callable thing) or a string that's going to be $eval
-ed in the scope's context. Not a getter, which will just return the object.
Try with
scope.$watch(function () { return authenticationService.user; },
function () { update(authenticationService.user); },
true); // use true to check for differences in object's properties.
Upvotes: 4