gpt4 book ai didi

angularjs - 如何将 NgModelController 传递给指令 Controller ?

转载 作者:行者123 更新时间:2023-12-02 18:54:38 25 4
gpt4 key购买 nike

我可以将 NgModelController 传递给指令 Controller 吗?这是必需的,以便我可以为 Controller 中的模型分配值。

这个例子不起作用:

   angular
.module('directives.selectBox', [])
.directive('selectBox', selectBox);

function selectBox() {
return {
restrict : 'E',
require : 'ngModel',
scope : {
list : '=',
},
replace : true,
templateUrl : 'common/directives/selectBox/selectBox.html',
controller : SelectBoxController,
};
}
function SelectBoxController(ngModel) {
ngModel.$setViewValue(10); // ???
}

最佳答案

实际上非常简单,您需要做的是将 $element 注入(inject) Controller ,然后调用 .controller() 函数来访问该元素它。

angular
.module('directives.selectBox', [])
.directive('selectBox', selectBox);

function selectBox() {
return {
restrict : 'E',
require : 'ngModel',
scope : {
list : '=',
},
replace : true,
templateUrl : 'common/directives/selectBox/selectBox.html',
controller : SelectBoxController,
};
}
function SelectBoxController($element) {
var ngModel = $element.controller('ngModel');
ngModel.$setViewValue(10); // ???
}

Angular 1.5 更新

请注意,在 AngularJS 1.5 中,除了现有的 directive() 函数之外,还添加了新的 component() 函数。该函数将配置对象作为第二个参数,允许您直接指定所需的 Controller ,然后将其绑定(bind)到组件的 Controller 。

下面再次使用相同的示例,但作为组件。

angular
.module('directives.selectBox', [])
.component('selectBox',
{
controller: SelectBoxController,
controllerAs: 'vm',
templateUrl : 'common/directives/selectBox/selectBox.html',
bindings: {
list: '=' // though '<' would be better
},
require: {
ngModel: '='
},
// replace: true ==> No longer possible with component
}
);

function SelectBoxController($element) {

$onInit() {
// This function is called automatically whenever the controller is ready
this.ngModel.$setViewValue(10); // ???
}
}

我希望我能正确地输入它,这个小小的文本区域几乎不是一个 IDE :)

关于angularjs - 如何将 NgModelController 传递给指令 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27786854/

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