简体   繁体   English

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

[英]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. 试图弄清楚为什么控制台告诉我一件事,而angular向html的输出却告诉我另一件事。

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 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 http://plnkr.co/edit/wxja7smqOJiSbUi7mfu4?p=preview

You need to bind your controller with $scope, like this: http://plnkr.co/edit/CV7rgBGQMnRlNDnYSQIq?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();

}

You need to use $scope and $scope.$apply to update values after the context has been rendered. 渲染上下文后,需要使用$scope$scope.$apply更新值。 tc ( this ) has no context in the lifecycle of the controller. tcthis )在控制器的生命周期中没有上下文。 In other words, your tc assignment is really just the function itself. 换句话说,您的tc分配实际上只是函数本身。 Not the binding context for the controller. 不是控制器的绑定上下文。

I have a forked version of your plnkr with a simple example to get it working. 我有您的plnkr的分叉版本,并提供了一个简单的示例来使其正常运行。

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

Docs for $scope and $apply can be found here: $scope$apply文档可在以下位置找到:

angular docs 角度文档

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

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