Susheel Singh Susheel Singh - 6 months ago 14
Ajax Question

unable to get updated scope value after ajax call

I tried the below code. I have searched for answers for answer and solutions to use $apply, $timeout but anything didn't work in my case. I am getting bunch errors.

JS:

var app = angular.module("test",[])
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html',
controller: 'loginCtrl'
})
});

app.controller("loginCtrl",["$scope","$http","$location",function($scope,$http,$sessionStorage,$location,$timeout) {
$scope.loginSuccess = false;
$scope.loginAuthencation = function(){
$http({
method: 'post',
url:'http://192.168.42.200:5000/authenticate',
data:{"username":$scope.username,"password":$scope.password}
}).then(function successCallback(successResponse) {
console.log(successResponse);
if(successResponse.data.status==="success"){
$scope.loginSuccess = true;
} else {
$scope.loginSuccess = false;
}
}, function errorCallback(response) {
$scope.loginSuccess = false;
});
}
}]);


index.html :

<p>{{loginSuccess}}</p>
<div ng-view></div>


login.html:

<div>
<img src="img/logo.png" alt="appicon"/>
</div>
<div class="sub-element">
<p><input type="text" name="username" placeholder="username" ng-model="username"/></p>
<p><input type="password" name="password" placeholder="password" ng-model="password"/></p>
</div>
<input type="checkbox" value="Remember Me" class="item-left"/>Remember Me
<p class="submit-btn"><input type="submit" id="login-form" value="Login" ng-click="loginAuthencation()" /></p>


value is not getting updated...

Answer

You have <p>{{loginSuccess}}</p> outside your ng-view. Therefore loginCtrl's scope won't be accessible. Either access <p>{{loginSuccess}}</p> inside login.html or use $rootScope.loginSuccess so that it works everywhere.

Comments