[英]How to update the view after changing the model in Angular?
如何讓Angular將我所做的更改傳播到模型中。 在AngularJS中,這將非常簡單,但我似乎無法讓它在Angular中運行。 我知道整個變化檢測系統和視圖傳播完全改變了。 不知何故,我需要通知角度變化。 但是我怎么能在實踐中做到這一點。
看到這段打字稿代碼:
import {Component, View, bootstrap, For} from 'angular2/angular2';
// Annotation section
@Component({
selector: 'app'
})
@View({
template: `
<div *for="#user of users">
{{user}}
</div>
`,
directives: [For]
})
class App {
users:Array<String>;
constructor() {
this.users = [];
this.fillUsersAsync();
}
fillUsersAsync(){
window['fetch']('http://jsonplaceholder.typicode.com/users')
.then( resp => resp.json())
.then( users => users.forEach(user => this.users.push(user.name)))
.then( () => console.log('Retrieved users and put on the model: ', this.users));
}
}
bootstrap(App);
您將看到,在用戶加載到模型后,視圖不會更新。
我正在使用systemjs 0.16,角度2.0.0-alpha.23。
請參閱此plnkr示例 (目前僅適用於chrome,因為使用了新的' fetch'api )
我發現了這個問題。 顯然,它是一個在alpha 27中修復的錯誤。請參閱此錯誤報告: https : //github.com/angular/angular/issues/1913
Angular2使用zonejs知道何時開始摘要循環(臟檢查和更新視圖)。 截至目前,在使用新的window.fetch()獲取數據后,不會觸發zonejs。
將窗口['fetch']行替換為this修復了我的問題: Zone.bindPromiseFn(window['fetch'])('http://jsonplaceholder.typicode.com/users')
要在AngularJS2中更新視圖中的數據,您應該使用Forms 。 您可以在此頁面閱讀此內容或在此處查看更多詳細信息。 如果我正確理解了表單,你應該修改你的@View部分,如下所示:
@View({
template: `
<div *for="#user of users" control="users">
{{user}}
</div>
`,
directives: [For]
})
--edited
試試這個:
import {Component, View, bootstrap, For} from 'angular2/angular2';
// Annotation section
@Component({
selector: 'app'
})
@View({
template: `
<div [control]="users" *for="#user of users">
{{user.value}}
</div>
`,
directives: [For, forms]
})
class App {
users:Array<String>;
constructor() {
this.users = new Control([]);
this.fillUsersAsync();
}
fillUsersAsync(){
window['fetch']('http://jsonplaceholder.typicode.com/users')
.then( resp => resp.json())
.then( users =>
var usersArr = []
users.forEach(user =>
usersArr.push(user.name))
this.users = new Control(usersArr));
}
}
bootstrap(App);
我不確定我的答案是否完全正確,但我找不到更多信息。 嘗試使用此代碼,力量可能與您同在! :)
我也找到了這個鏈接 , 非常有用。
據我所知,在構造函數中,您應該通過new Control(some data)
初始化您的users
變量,然后在視圖模板中,您可以像這樣訪問這些數據 - {{users.value}}
。
如果它不起作用:嘗試相同但使用非常簡單的數據,例如使用字符串而不是數組。
此視頻將有助於在ng2中展示表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.