带有隔离范围的指令绑定有时不在范围内 [英] Bindings on directive with Isolate scope not in scope sometimes
问题描述
所以我有指令 隔离范围和 controllerAs 模式。
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;
}
}
问题是如果我在<$之前断点c $ c> init()方法 vm.something
的定义应该是在 productsReady $中c $ c>函数未定义。
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.
这是正常行为吗? promise是否在不同的范围内解析代码?
Is that a normal behaviour? Is the promise resolving code in a different scope?
推荐答案
使用 $ onInit
生命周期挂钩以保证绑定时间:
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
这篇关于带有隔离范围的指令绑定有时不在范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!