【发布时间】:2016-08-09 15:17:07
【问题描述】:
我有一个用相当基本的 JS 制作的非 Angular 页面,并认为尝试添加一些 Angular2 并将其用于一些新功能是一个绝妙的主意。
我的计划是我将一个 Angular2 组件绑定到一个由旧代码更新的对象,然后我会使用 Angular2 魔法来更新一大块 UI。
问题是我无法说服 Angular2 对外部 JS 中所做的任何更改做出反应。这样做有什么诀窍?在谷歌上搜索这个问题的尝试导致了对 Angular2 的变化检测过程的深入解释,这到目前为止还没有帮助。这只是一个糟糕的想法吗?
我发现了一个随机的 Angular2 jsfiddle 并将其破解以显示问题。字符串被添加到“window.names”中,但在从角度侧添加一个字符串之前您看不到它们:https://jsfiddle.net/byfo3jg3/。代码如下:
var names = ['Joe'];
setTimeout(function() {
names.push("Frank");
}, 1000);
setTimeout(function() {
names.push("Sterve");
}, 2000);
setTimeout(function() {
names.push("Garfield");
}, 3000);
(function() {
var HelloApp,
ListThing;
ListThing = ng
.Component({
selector: 'list-thing',
template: '<ul><li *ng-for="#name of names">{{name}}</li></ul>',
directives: [ng.NgFor]
})
.Class({
constructor: function() {
this.names = window.names;
setTimeout(function() {
this.names.push("Oh hai");
}.bind(this), 10000);
}
});
HelloApp = ng
.Component({
selector: 'hello-app',
template: '<list-thing></list-thing>',
directives: [ListThing]
})
.Class({
constructor: function() {}
});
document.addEventListener('DOMContentLoaded', function() {
ng.bootstrap(HelloApp);
});
}());
【问题讨论】:
-
我不建议这样做,除非你绝对必须这样做!否则,查看 Observables 并订阅组件中该数组的更改,当更改发生时更新组件数组。
标签: data-binding angular angular2-changedetection