[英]Two-way binding is not woking
我在綁定角度數據時遇到問題。
我的模特:
<div id="ng-app-MyApp">
<ng-view></ng-view>
</div>
控制器:
angular.module("MyApp.controllers", []).
controller("myController", function($scope, service) {
$scope.someprop = "12";
$scope.nameFilter = "text here";
$scope.val = "";
setTimeout(function() {
$scope.val = "321";
}, 1000);
$.when(service.getItems()).done(function (items) {
console.log(items.length);
$scope.someprop = "hello";
});
});
index.html的:
<div>
<input type="text" ng-model="nameFilter" />
<div>{{nameFilter}}</div>
<table>
<tr>
<td>{{someprop}}</td>
<td>{{val}}</td>
</tr>
</table>
</div>
我使用手動綁定( angular.bootstrap($("#ng-app-MyApp")[0], ["MyApp"]);
)。 service.getItems()
返回jQuery延遲對象。 當頁面加載時,我希望someprop
值變為“ hello”,而val
將等於“ 321”。 但是實際上什么也沒發生。 當我開始在文本框中鍵入內容時,將執行數據綁定,並且可以在UI上看到someprop =“ hello”和val =“ 321”。
我不知道為什么為什么不自動更新此屬性,而是僅當我開始在文本框中鍵入內容時才自動更新?
添加$scope.$apply()
$.when(service.getItems()).done(function (items) {
console.log(items.length);
$scope.someprop = "hello";
$scope.$apply();
});
您需要調用它,因為您是在angular的框架(jquery)之外處理回調,並且不會引發刷新依賴項的事件。
$apply
是“重新加載/刷新”綁定的函數
如果可能的話,我建議您嘗試避免在角度代碼中使用jQuery
如果service.getItems()
是一個簡單的ajax請求,請使用$http
angular的服務而不是jQuery並按如下所示編輯您的自定義服務:
服務:
...
service.getItems = function()
{
return $http.get('<url>');
};
...
控制器:
service.getItems()
.success(function(data)
{
console.log(items.length);
$scope.someprop = "hello";
});
請注意,使用純角度,您無需添加$apply()
您會錯過$ digest進程,該進程負責angularjs中的雙向數據綁定(盡管當您使用純angularjs可以實現完全相同的目的時,為什么還要麻煩地使用jQuery進行諾言)
避免您可以通過幾種方式做到這一點
$.when(service.getItems()).done(function (items) {
console.log(items.length);
$scope.apply(function(){
$scope.someprop = "hello";
})
});
$.when(service.getItems()).done(function (items) {
console.log(items.length);
$timeout(function(){
$scope.someprop = "hello";
})
});
$.when(service.getItems()).done(function (items) {
console.log(items.length);
$scope.someprop = "hello";
$scope.$digest()
});
盡管最后一個比較棘手,但是如果應用很大並且摘要發生的頻率更高,則可能會引發錯誤digest already in progress
兩項未設置,因為它們錯過了摘要。 您要使用數據綁定的所有內容都必須通過服務來完成。
要覆蓋此內容,您需要執行以下操作:
setTimeout(function() {
$scope.$apply(function () {
$scope.val = "321";
});
}, 1000);
$.when(service.getItems()).done(function (items) {
console.log(items.length);
$scope.$apply(function () {
$scope.someprop = "hello";
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.