可以将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
原文地址:https://www.jb51.cc/angularjs/142663.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。