繁体   English   中英

角度-为什么在此函数内部未更新范围

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

试图弄清楚为什么控制台告诉我一件事,而angular向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

您需要使用$ 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();

}

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

我有您的plnkr的分叉版本,并提供了一个简单的示例来使其正常运行。

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

$scope$apply文档可在以下位置找到:

角度文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM