Javascript 指令作用域未在异步上更新
在这里,这似乎是一个相当常见的问题,但我似乎不能用Angular中的自定义指令来处理数据绑定。我使用的是1.4.8,这是我的代码:Javascript 指令作用域未在异步上更新,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,在这里,这似乎是一个相当常见的问题,但我似乎不能用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> 现在,我的指令
<p data-ng-show="!main.resolved">Loading...</p>
<my-directive data-ng-hide="!main.resolved"
data-file-reads="main.reads"></my-directive>
现在,我的指令的代码只是监听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
});
}]
};
});
angular.module('myApp')
.directive('myDirective',函数(){
返回{
限制:'E',
范围:{
文件读取:'='
},
模板:“”,
bindToController:对,
controllerAs:'ctrl',
控制器:['$scope','files',函数($scope,files){
const controller=this;
$scope.$watch('fileReads',函数(newVal){
console.log(newVal);//仅触发一次
});
}]
};
});
我只得到一个值为未定义的控制台.log
。当$http
承诺解析并且fileReads
的值在MainCtrl
上更新时,我没有得到指令控制器的更新
现在,我已经有足够多的时间用这种问题碰壁,怀疑这与$scope.$apply
和$digest
循环有关,但我不是从外部源或任何东西更新我的作用域
有什么提示吗?我还没有找到关于具体原因的更多信息(我一定会在我找到的时候编辑这篇文章),但是现在,在函数调用中包装我的watch表达式做到了这一点(我还用$watchCollection
替换了我的$watch
,但这只是次要的):
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
});
}]
};
});
$scope.$watchCollection(() => this.fileReads, newVal => console.log(newVal));