angularjs – 如何将NgModelController传递给指令控制器?
发布时间:2020-12-17 07:38:54 所属栏目:安全 来源:网络整理
导读:可以将NgModelController传递给指令控制器吗?这是必需的,所以我可以分配值到控制器中的模型. 此示例不起作用: angular .module('directives.selectBox',[]) .directive('selectBox',selectBox); function selectBox() { return { restrict : 'E',require :
可以将NgModelController传递给指令控制器吗?这是必需的,所以我可以分配值到控制器中的模型.
此示例不起作用: 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); // ??? }
实际上很简单,你需要做的是通过将$元素注入到控制器中,然后调用.controller()函数来访问元素.
angular .module('directives.selectBox',[]) .directive('selectBox',selectBox); function selectBox() { return { restrict : 'E',scope : { list : '=',}; } function SelectBoxController($element) { var ngModel = $element.controller('ngModel'); ngModel.$setViewValue(10); // ??? } 角度1.5更新 请注意,在AngularJS 1.5中,除了现有的directive()函数之外,还添加了新的component()函数.此功能将配置对象作为第二个参数,允许您直接指定所需的控制器,然后将其绑定到组件的控制器. 下面是同一个例子,但是作为组件. angular .module('directives.selectBox',[]) .component('selectBox',{ controller: SelectBoxController,controllerAs: 'vm',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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |