异步上未更新指令作用域
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
周期有关,但我没有从外部来源或任何东西更新我的范围。
有什么提示吗?
我还没有找到更多关于具体原因的信息(我一定会在编辑这篇文章时编辑它),但现在用函数调用包装我的手表表达式做到了(我也用$watchCollection
替换了我的$watch
,但这只是次要的):
$scope.$watchCollection(() => this.fileReads, newVal => console.log(newVal));
相关文章:
- 如何将多槽transclude作用域设置为指令作用域
- 指令作用域始终为空
- 如何在angularjs中访问一个指令作用域值到另一个指令
- AngularJS指令作用域未解析(“属性名称未定义”错误)
- 角度指令作用域绑定在 ng-repeat中不起作用
- 指令 作用域更改时无法触发
- 角度JS指令作用域变量关系
- 如何使用用@定义的指令作用域生成ng-if
- 使用指令作用域变量呈现的动态模板
- 在指令作用域和控制器$scope之间共享数据
- 在没有自己的控制器的情况下使用指令作用域何时合适
- 是否可以链接指令作用域(例如obj.prop)
- 与控制器在同一元素中的自定义指令作用域
- 将指令作用域值绑定到HTML
- AngularJS-获取一个输入值并将其传递给父指令作用域
- 正在与子指令作用域共享作用域对象
- angularjs中没有更新指令作用域变量
- 如何从控制器调用指令作用域上的函数
- 从控制器外部访问指令作用域
- 异步上未更新指令作用域