[英]Directive scope not updated on async
這似乎是一個相當普遍的問題,但是我似乎無法用Angular中的自定義指令來圍繞數據綁定。 我正在使用1.4.8,這是我擁有的代碼:
<p data-ng-show="!main.resolved">Loading...</p>
<my-directive data-ng-hide="!main.resolved"
data-file-reads="main.reads"></my-directive>
main.reads
的值是通過MainCtrl
上的$http
檢索的:
angular.module('myApp')
.controller('MainCtrl', ['$http', '$scope', function($http, $scope) {
this.resolved = false;
this.currentTab = 0;
$http.get('/my/api/call').then(res => {
this.reads = res.data.file_reads;
this.writes = res.data.file_writes;
this.resolved = true;
});
$scope.$watch('main.reads', new => console.log(new)); // triggered twice
}]);
現在,我指令的代碼只是偵聽fileReads
屬性上的更改:
angular.module('myApp')
.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
fileReads: '='
},
template: '<div></div>',
bindToController: true,
controllerAs: 'ctrl',
controller: ['$scope', 'files', function($scope, files) {
const controller = this;
$scope.$watch('fileReads', function(newVal) {
console.log(newVal); // only triggered once
});
}]
};
});
我只得到一個帶有undefined
值的console.log
。 當$http
承諾解析並且fileReads
上的MainCtrl
值更新時,指令控制器上沒有更新。
現在,我已經用這種問題將頭撞牆了很多次,以至懷疑這與$scope.$apply
和$digest
循環有關,但是我沒有從外部更新范圍來源或其他任何內容。
有什么提示嗎?
我還沒有找到具體原因的詳細信息(我一定會編輯這篇文章時,我做的),但現在包裹在一個函數調用我的手表式做到了(我也換成我的$watch
用$watchCollection
,但這只是次要的):
$scope.$watchCollection(() => this.fileReads, newVal => console.log(newVal));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.