AngularJS authentication service + watcher -
i making authentication app , i've been struggling getting service work properly. have simplified code.
the service:
app.factory('authenticationservice', function() { var isloggedin = false; return { isloggedin : function() { return isloggedin; } } });
maincontroller:
app.controller('maincontroller', [ '$scope', 'authenticationservice', function( $scope, authenticationservice ) { $scope.isloggedin = authenticationservice.isloggedin(); $scope.$watch('authenticationservice.isloggedin()', function (newval, oldval) { console.log("detected change in service."); if( newval !== oldval ) { $scope.isloggedin = newval; } }); }]);
logincontroller:
// login http request successful, returns positive answer // want change variable in service true authenticationservice.isloggedin = true;
main problem: way service variable modified logincontroller right - not reflected in watcher , not sure if changes variable in service. wrong there?
the goal: instant change in view after successful login (ng-show).
any other constructive criticism towards code welcome.
there several ways.
1) use broadcast events
2) create scope service:
app.factory('authenticationservice', function($rootscope) { var isloggedin = false; var authenticationservice = $rootscope.$new(); return authenticationservice; });
3) watch property:
app.factory('authenticationservice', function() { return { isloggedin : false } }); // in controller: $scope.$watch('authenticationservice.isloggedin', function(){...
4) write custom watcher:
app.factory('authenticationservice', function() { var isloggedin = false; return { isloggedin : function() { return isloggedin; } } }); // in controller $scope.$watch(function(){return authenticationservice.isloggedin()}, function(){...
Comments
Post a Comment