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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -