gpt4 book ai didi

javascript - 将指令隔离范围绑定(bind)传递到其 Controller `this` 上下文 (AngularJS V1.6)

转载 作者:太空宇宙 更新时间:2023-11-04 15:53:58 25 4
gpt4 key购买 nike

如何将指令参数传递给其 Controller ?

我使用指令:

<directive value="ctrl.item"></directive>

.directive('directive', [ function () {
return {
restrict: 'AE',
scope: {
value: '=value'
},
templateUrl: 'item.html',
controller: 'Item as item'
};
}])

我想读value在指令的 Controller 内:

.controller('Item', [function Item () {

console.log(this.value);
}])

是否可以使用this来做到这一点

最佳答案

设置bindToController propertytrue

.directive('directive', [ function () {
return {
restrict: 'AE',
scope: {
value: '=value'
},
//USE bindToController
bindToController: true,
templateUrl: 'item.html',
controller: 'Item as item'
};
}])

bindToController

This property is used to bind scope properties directly to the controller. It can be either true or an object hash with the same format as the scope property.

When an isolate scope is used for a directive (see above), bindToController: true will allow a component to have its properties bound to the controller, rather than to scope.

After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller properties. You can access these bindings once they have been initialized by providing a controller method called $onInit, which is called after all the controllers on an element have been constructed and had their bindings initialized.

— AngularJS Comprehensive Directive API Reference

<小时/>

使用$onInit生命周期钩子(Hook)

.controller('Item', function Item () {
this.$onInit = function() {
console.log(this.value);
};
})

$compile:

Due to bcd0d4, pre-assigning bindings on controller instances is disabled by default. It is still possible to turn it back on, which should help during the migration. Pre-assigning bindings has been deprecated and will be removed in a future version, so we strongly recommend migrating your applications to not rely on it as soon as possible.

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.

— AngularJS Developer Guide - Migrating from V1.5 to V1.6

关于javascript - 将指令隔离范围绑定(bind)传递到其 Controller `this` 上下文 (AngularJS V1.6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867670/

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