angularjs – 如何将NgModelController传递给指令控制器?

可以将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

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...