mls3590712
mls3590712

Reputation: 810

Angular - why is the scope not updated inside of this function

Trying to figure out why when the console tells me one thing but angular's output to html tells me another.

Code

angular.module('global',[]);

angular.module('global').controller('thisTestController', thisTestController);
function thisTestController() {
  var tc = this;  
  tc.status = "not loaded";

  function activate() {

    var background = new Image();
    background.onload = function () {
        tc.status = "loaded";
        console.log(tc.status);
    };
    background.src = 'http://placehold.it/350x150';

  }

  activate();

}

HTML

  <body ng-app="global">
     <div ng-controller="thisTestController as tc">Status = {{tc.status}}</div>
  </body>

Result

Console.log - loaded
HTML - Status = not loaded

http://plnkr.co/edit/wxja7smqOJiSbUi7mfu4?p=preview

Upvotes: 2

Views: 698

Answers (2)

LYu
LYu

Reputation: 2416

You need to bind your controller with $scope, like this: http://plnkr.co/edit/CV7rgBGQMnRlNDnYSQIq?p=preview

angular.module('global', []);

angular.module('global').controller('thisTestController', thisTestController);

function thisTestController($scope) {
  var tc = this;
  tc.status = "not loaded";

  function activate() {

    var background = new Image();
    background.onload = function() {
      tc.status = "loaded";
      $scope.$apply();
      console.log(tc.status);
    };
    background.src = 'http://placehold.it/350x150';

  }

  activate();

}

Upvotes: 4

technicallyjosh
technicallyjosh

Reputation: 3531

You need to use $scope and $scope.$apply to update values after the context has been rendered. tc (this) has no context in the lifecycle of the controller. In other words, your tc assignment is really just the function itself. Not the binding context for the controller.

I have a forked version of your plnkr with a simple example to get it working.

http://plnkr.co/edit/fghSbSsarBbM0zv5EzoB?p=preview

Docs for $scope and $apply can be found here:

angular docs

Upvotes: 1

Related Questions