user1245524 user1245524 - 1 month ago 6
AngularJS Question

need to display error message on the view, the error message is set in controller

Trying to display the error message on the view, when the service call from controller results in 404 the path is redirected to the login page view and the error message is set in $scope to view when 404 occurs.

below is the controller code which set the error message in $scope when 404 occurs

angular.module('app.controllers').controller('contactLoginCtrl',['$rootScope','$scope','AuthenticateService','$location',function($rootScope,$scope,AuthenticateService,$location){


$scope.authenticate = function(userModel){
var userName = userModel.username;
var password = userModel.password;
console.log(userName+password);
var result = AuthenticateService.checkUser(userName,password);

result.then(function(response){
console.log(response);

},function(error){

if(error.status== '404'){

// ***below is the erroMssg which has to show on the view,
after setting the message it being redirected to login view***

$scope.errorMsg = "your request not been processed";
$location.path('/');
}
})

};


}]);

In the view i am placing the errorMsg expression as {{errorMsg}}

This is not working could anybody please suggest me any workout ? thanks in advance

Answer

Most likely, it is an issue with the scope digest cycle. Here is a simple working copy of your scenario, with the data being fetched from the service. you might solve your problem by having $scope.digest() once the errMsg is set in the ajax error callback.

var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope", "sampleService",
  function($scope, sampleService) {

    sampleService.sampleMethod(1).then(function() {
      console.log("Success");
    }, function(error) {
      if (error.status == '400') {
        $scope.errMsg = "Unauthorized User. Please login to continue";
      }
      $scope.$digest();
    });
  }
]);

app.service("sampleService", function() {
  this.sampleMethod = function(value) {
    var promise = new Promise(function(resolve, reject) {
      setTimeout(function() {
        value = value * 2;
        reject({
          status: 400,
          message: "UnAuthorized"
        });
      }, 1000);
    });
    return promise;
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    {{errMsg}}
  </div>
</div>