Can i pass NgModelController to directive controller? That's required so i can assign values to model in controller.
This example does not work:
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); // ???
}
Note: When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option. The restrict option is typically set to: 'A' - only matches attribute name. 'E' - only matches element name.
A controller is usually used to contain and maintain the logic for your view, which gets bound to your view via $scope. A directive is something that you might use repeatedly and is called in your view directly through the directive name which you can pass in as an attribute.
Answer:The link option is just a shortcut to setting up a post-link function. controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.
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); // ???
}
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); // ???
}
}
I hope I typed it out ok, this tiny textarea is hardly an IDE :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With