I can't get $scope.$apply to work in AngularJS

I cannot seem to get $scope.$watch() to work in AngularJS. I am attempting to "watch" a variable contained within a service. The variable is being set by one controller, and I want to act on that variable change within another server. Any advice as to what I am doing wrong would really be appreciated. Here is my code: (one note: in the Index.cshtml code, if I remove the "data-ng-show" condition from the div, then the div is shown. So I know that the error has something to do with the data-ng-show="loggedIn" condition.)

//In services.js file: function Session() { this.loggedIn = false; this.updateLogIn = function (value) { this.loggedIn = value; } } angular.module('app.services', []).service('session', [Session]);

angular.module('app.controllers', []) .controller('HomeCtrl', ['$scope', 'session', function ($scope, session) { $scope.loggedIn = session.loggedIn; $scope.$watch( function () { session.loggedIn; }, function (newVal, oldVal) { if (newVal != undefined) { $scope.loggedIn = newVal; } }, true ); }]) .controller('LoginCtrl', ['$scope', 'session', function ($scope, session) { $scope.loggedIn = session.loggedIn; $scope.login = function () { var s = "UserName=" + $scope.userName + "&Password=" + $scope.password; $.ajax({ type: "POST", url: "http://localhost:50227/api/Authentication", data: s }) .fail(function () { session.updateLogIn(false); }) .done(function (data) { var tmp = JSON.parse(data); // do stuff with sessionStorage... session.updateLogIn(true); }) .always(function () { $scope.loggedIn = session.loggedIn; $scope.$apply(); }) }; $scope.logout = function () { session.updateLogIn(false); $scope.loggedIn = false; } }])

//In Login.cshtml file: <form id="frmLogin" class="form-inline search-box" data-ng-controller="LoginCtrl" ng-submit="login(userName, password)"> <div data-ng-hide="loggedIn"> <input id="UserName" ng-model="userName" type="text" placeholder="Username or Email" required autofocus /> <input id="Password" ng-model="password" type="password" placeholder="Password" required /> <button type="submit" ng-disabled="!(userName && password)" disabled>Sign In</button> </div> <div data-ng-show="loggedIn"> <a href="#" style="color:white;">Sign out</a> </div>

//In Index.cshtml file: <div data-ng-controller="HomeCtrl"> <div data-ng-show="loggedIn"> <p>This should show when the user is logged in</p> </div>

-------------Problems Reply------------

On first sight there is a problem in the $watch, the function should return a value! Please provide a plunker next time!

function () {
return session.loggedIn;

Category:javascript Views:1 Time:2019-01-09

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.173 (s). 11 q(s)