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

标签 angularjs angularjs-directive angularjs-scope

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

相关文章:

javascript - AngularJs 将模型值+模型名称传递给 Controller ​​中的函数

javascript - 如何在 Firefox 调试器中找到该变量的值?

javascript - 复制 $rootScope

angularjs - 如何为服务中的函数模拟局部变量? Jasmine /karma 测试

Angularjs templateUrl 无法绑定(bind) ng-repeat 内的属性

javascript - 使用 Angular ui 在子范围之前加载父范围

javascript - 当范围变量依赖于 AngularJS 中的服务时,何时更新?

javascript - angular js从范围div和span元素中选择所有文本以让用户复制所选文本

javascript - AngularJS + ADAL.JS 设置资源 ID(受众)

javascript - 指令中的 AngularJS 模板与 templateURL