javascript – 带有隔离范围的指令绑定有时不在范围内
作者:互联网
所以我有一个带隔离范围和controllerAs模式的指令.
var directive = {
restrict: 'E',
scope: {
something: '='
},
templateUrl: './App/directiveTemplate.html',
controller: directiveController,
controllerAs: 'vm',
bindToController: true
}
并在控制器中初始化,使用返回promise的$http调用REST服务.
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函数中它是未定义的.
这是正常的行为吗?承诺是否解决了不同范围内的代码?
解决方法:
使用$onInit
Life-Cycle Hook保证绑定的时间:
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;
}
}
来自Docs:
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.06001
07001
标签:javascript,angularjs,angularjs-directive,angularjs-scope 来源: https://codeday.me/bug/20190929/1834233.html