Search code examples
javascriptangularjsangularjs-controllerangularjs-factory

AngularJS : Controller is not getting updated factory value


I'm updating an object property in a factory and it doesn't seem to be updating the property referenced in the controller.

Say I have a factory that looks something like this...

app.factory('User', function ($http)
{  
 $http.defaults.useXDomain = true;

    var User = {
        Name: "",
        JobTitle: "",
        isloaded: false
    };

User.GetUser = function (ID)
{
       $http(
            {
                url: "webservice uri",
                method: "GET"
            }
        ).success(function(data, status, headers, config)
        {               
            User.isloaded= true;

        }).error(function(data, status, headers, config)
        {

        })      
}
return User;
});

the property 'isloaded' is initially set to false, and then once the $http calls goes through the success callback, it is eventually set to false.

And then I have a controller that looks something like

controllers.DefaultCtrl = function($scope, User)
{ 
    $scope.showMessage = User.isloaded;
    $scope.getUser = function ()
    {
        User.GetUser("11111");
    }
    $scope.getUser();   
    }

which is associated with this html

<h1>{{showMessage.isloaded ? 'success' : 'Loading...'}}</h1>

Ultimately I would like it to say 'success', however, the text never changes in the html


Solution

  • The issue is that you are assigning a primitive:

     $scope.showMessage = User.isloaded;
    

    showMessage is assigned to false, it is not "pointing" to the isloaded property.

    What you should probably do is set the User to be a scope variable, something like:

    controllers.DefaultCtrl = function($scope, User)
    { 
      $scope.user = User;
      $scope.user.getUser("11111");   
    }
    

    and then in your html you can do:

    <h1>{{user.isloaded ? 'success' : 'Loading...'}}</h1>