I would like to define both controller, and require on a directive. Something like this:
return {
controller: 'ValidateElementCtrl as validate',
require: 'ngModel',
scope: {
ngModel: '='
},
link: link
};
Now when defining either controller, or requiring ng model, in the link function you get access only to the fourth argument. I know that the fourth argument can be an object and contain multiple controllers and such, but that's in case when you are defining the controllers as an array.
This is what I have and I don't know how to access the controller, I get the required ngModel as a fourth argument:
function link(scope, element, attrs, ctrlGetsNgModel) {
console.log(ctrlGetsNgModel) // Returns the ngModel, no sign on the controller
}
I know I could define a controller on a directive, and pass it in as a scope property, but in this case I would like to define a controller for the directive which would handle the validation and similar, and that controller would be assigned only to this directive.
EDIT: Found a way how to do this: To have both ngModel and controller in the link function you can assign the controller to the template like this:
Then define the scope access to the someDirectiveName: '=', and you can access the controller on your directive scope `scope.someDirectiveName' =< the controller scope.
Not exactly sure what you are trying to achieve but I don't think you can put 'controller as' in a string like that in a directive definition. Use the controllerAs
property, so something like:
return {
// ...
controller: controller,
controllerAs: 'validate'
// ....
};
You will to also use bindToController: true
if you want to access any properties defined on an isolate scope. But I'm not sure if you need an isolate scope at all..
Could you clarify what your actual goal is? Is this what you are aiming for???
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
}
});