Isolate 范围内的指令绑定有时不在范围内 [英] Bindings on directive with Isolate scope not in scope sometimes
问题描述
所以我有一个带有隔离作用域和controllerAs模式的指令.
So I have a directive with isolate scope and a controllerAs pattern.
var directive = {
restrict: 'E',
scope: {
something: '='
},
templateUrl: './App/directiveTemplate.html',
controller: directiveController,
controllerAs: 'vm',
bindToController: true
}
在控制器中,我使用返回承诺的 $http 调用 REST 服务进行初始化.
and in the controller I init with a call to a REST service using $http that returns a promise.
function directiveController(someService) {
var vm = this;
// Here vm.something is defined and bound to the appropriate model set where the directive is used
init()
function init() {
return someService.getProducts()
.then(productsReady);
function productsReady(response) {
vm.products = response;
//find product using vm.something
// here vm.something is undefined
return vm.products;
}
}
问题是,如果我在 init()
方法之前断点 vm.something
被定义为它应该是但在 productsReady
函数未定义.
The problem is that if I breakpoint before the init()
method vm.something
is defined like it should be but in the productsReady
function it is undefined.
这是正常行为吗?承诺在不同的范围内解析代码吗?
Is that a normal behaviour? Is the promise resolving code in a different scope?
推荐答案
使用 $onInit
Life-Cycle Hook 保证绑定的时间:
Use the $onInit
Life-Cycle Hook to guarantee the timing of bindings:
function directiveController(someService) {
var vm = this;
̶i̶n̶i̶t̶(̶)̶
this.$onInit = init;
function init() {
return someService.getProducts()
.then(productsReady);
function productsReady(data) {
vm.products = data;
return vm.products;
}
}
来自文档:
依赖于绑定存在的初始化逻辑应该放在控制器的$onInit()
方法中,保证总是在绑定被分配后被调用.
Initialization logic that relies on bindings being present should be put in the controller's
$onInit()
method, which is guaranteed to always be called after the bindings have been assigned.
.component('myComponent', {
bindings: {value: '<'},
controller: function() {
this.$onInit = function() {
// `this.value` will always be initialized,
// regardless of the value of `preAssignBindingsEnabled`.
this.doubleValue = this.value * 2;
};
}
})
—AngularJS 开发人员指南 - 迁移到 V1.6 - $compile
这篇关于Isolate 范围内的指令绑定有时不在范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!