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

问题描述:

我可以将 NgModelController 传递给指令控制器吗?这是必需的,因此我可以为控制器中的模型分配值.

Can i pass NgModelController to directive controller? That's required so i can assign values to model in 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 注入你的控制器然后调用来访问元素.controller() 函数.

Pretty simple actually, what you need to do is to get access to the element by injecting $element into your controller and then calling the .controller() function on it.

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() 函数.此函数将 configuratoin 对象作为第二个参数,允许您直接指定所需的控制器,然后将其绑定到组件的控制器.

Angular 1.5 update

Note that in AngularJS 1.5 the new component() function was added in addition to the existing directive() function. This function takes a configuratoin object as second parameter that allows you to directly specify the required controllers, which will then be bound to the component's controller.

再次在同一个例子下,但作为组件.

Below the same example again, but as component.

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 :)

I hope I typed it out ok, this tiny textarea is hardly an IDE :)