如何访问指令上的 require: 'ngModel' 和 controller 属性

How to access both require: 'ngModel' and controller properties on directive

我想同时定义控制器和指令要求。像这样:

return {
    controller: 'ValidateElementCtrl as validate',
    require: 'ngModel',
    scope: {
        ngModel: '='
    },
    link: link
};

现在,在 link 函数中定义控制器或需要 ng 模型时,您只能访问第四个参数。我知道第四个参数可以是一个对象并包含多个控制器等,但是当您将控制器定义为数组时就是这样。

这就是我所拥有的,但我不知道如何访问控制器,我得到了所需的 ngModel 作为第四个参数:

function link(scope, element, attrs, ctrlGetsNgModel) {
    console.log(ctrlGetsNgModel) // Returns the ngModel, no sign on the controller
}

我知道我可以在指令上定义一个控制器,并将其作为范围传递 属性,但在这种情况下,我想为指令定义一个控制器来处理验证和类似操作,并且该控制器将仅分配给该指令。

编辑: 找到了如何做到这一点的方法: 要在 link 函数中同时拥有 ngModel 和控制器,您可以像这样将控制器分配给模板:

然后定义对 someDirectiveName: '=' 的范围访问,您可以在指令范围内访问控制器 `scope.someDirectiveName' =< 控制器范围。

不确定您要实现的目标,但我认为您不能将 'controller as' 放入指令定义中那样的字符串中。使用 controllerAs 属性,例如:

return {
    // ...
    controller: controller,
    controllerAs: 'validate'
    // ....
};

如果您想访问隔离作用域上定义的任何属性,您也将使用 bindToController: true。但我不确定你是否需要一个隔离范围..

能否说明一下您的实际目标是什么?这是你的目的吗???

DEMO

html

<body ng-controller="MainCtrl">
    <foo ng-model="someModel"></foo>
</body>

js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  // the element on which you apply the directive will need to have a model
  // defined if you use `require: 'ngModel'`
  $scope.someModel = {modelValue: 'blah'};
});


app.directive('foo', function(){
  return {
    controller: controller,
    controllerAs: 'validate',
    template: '<div>{{validate.someProp}}</div>',
    require: 'ngModel',

    link: link

  };

  function controller(){ 
    this.someProp = 'bar';
  }

  function link(scope, element, attrs, ctrlGetsNgModel) {
      console.log('ctrlGetsNgModel',ctrlGetsNgModel) // Returns the ngModel, no sign on the controller
  }

});

假设您的指令名称是 "validateField",那么您可以像这样传递一个数组:

return {
    controller: controller,
    controllerAs: 'validate',
    require: ['ngModel', 'validateField'],
    scope: {
        ngModel: '='
    },
    link: link
};

然后在 link 函数中,第四个参数将是一个包含 ngModel 控制器和指令控制器的数组。

function link(scope, element, attrs, ctrlArray) {
    console.log(ctrlArray[0]) // Returns the ngModel controller
    console.log(ctrlArray[1]) // Returns your controller
}