ES6承诺不更新AngularJS DOM [英] ES6 Promise not Updating AngularJS DOM
问题描述
我无法理解角度组件范围。如果我这样做:
I'm having trouble understanding angular components scope. If I do something like:
function myComponent(){
this.data = 'Hello World';
}
let myModule = angular.module('myModule', []);
myModule.component('myComponent', {
template: `<div>{{$ctrl.data}}</div>`,
controller: myComponent
});
<script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="myModule">
<my-component></my-component>
</div>
它打印得很好......现在,如果我进行一些小修改并使其异步:
It prints it just fine... Now, if I do a small modification and make it async:
function myComponent(){
Promise.resolve().then(_ => {
this.data = 'Hello World';
});
}
let myModule = angular.module('myModule', []);
myModule.component('myComponent', {
template: `<div>{{$ctrl.data}}</div>`,
controller: myComponent
});
<script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="myModule">
<my-component></my-component>
</div>
它不会打印任何内容。我可以通过点击处理程序改变值,但是对于http和其他异步操作,它将无法工作。
It doesn't print anything. I can change the value with click handlers thouogh, but for http and other async operations it won't work.
推荐答案
当你运行异步代码,您需要让Angular知道某些内容已更新。这使得angular运行$ digest循环,检查是否有任何绑定需要更新。
When you run asynchronous code, you need to let Angular know that something has updated. This makes angular run a $digest cycle, checking if any bindings need updating.
为此,请将您的作业包装在对 $ scope的调用中。$ apply()
。
To do this, wrap your assignment in a call to $scope.$apply()
.
function myComponent($scope){
Promise.resolve().then(_ => {
$scope.$apply(() => {
this.data = 'Hello World';
});
});
}
let myModule = angular.module('myModule', []);
myModule.component('myComponent', {
template: `<div>{{$ctrl.data}}</div>`,
controller: myComponent
});
<script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="myModule">
<my-component></my-component>
</div>
请注意,我不仅在函数体中添加了 $ scope
,还将其作为函数参数添加。
Notice that I added $scope
not only in the function body, but also as a function parameter.
了解更多关于 $ scope。$申请
和 $ scope.digest
这篇关于ES6承诺不更新AngularJS DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!