gpt4 book ai didi

javascript - 与隔离范围指令的绑定(bind)有时不在范围内

转载 作者:行者123 更新时间:2023-12-03 03:21:12 25 4
gpt4 key购买 nike

所以我有一个带有隔离范围controllerAs模式的指令

    var directive = {
restrict: 'E',
scope: {
something: '='
},
templateUrl: './App/directiveTemplate.html',
controller: directiveController,
controllerAs: 'vm',
bindToController: true
}

在 Controller 中,我使用返回 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 中函数未定义。

这是正常行为吗? promise 解析代码是否在不同的范围内?

最佳答案

使用$onInit Life-Cycle Hook保证绑定(bind)的时间:

 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;
}
}

来自文档:

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 Developer Guide - Migrating to V1.6 - $compile

关于javascript - 与隔离范围指令的绑定(bind)有时不在范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46568520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com