Angular - 为什么范围未在此函数内更新

时间:2015-11-18 22:39:04

标签: javascript angularjs

试图找出为什么当控制台告诉我一件事但是有角度的输出到html告诉我另一件事。

代码

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>

结果

Console.log - loaded
HTML - Status = not loaded

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

2 个答案:

答案 0 :(得分:3)

您需要使用$ scope绑定控制器,如下所示: 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();

}

答案 1 :(得分:1)

在呈现上下文后,您需要使用$scope$scope.$apply来更新值。 tcthis)在控制器的生命周期中没有上下文。换句话说,你的tc赋值实际上只是函数本身。不是控制器的绑定上下文。

我有一个plnkr的分叉版本,有一个简单的例子可以让它工作。

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

$scope$apply的文档可以在此处找到:

angular docs