I have a custom form element directive that includes some child directives. I require ngModel
in the parent directive so that I can use ng-model="object.data"
on the directives HTML declaration.
The problem I have is changing that value from the child directives. The child directives can require the parents controller function but that controller function does not have access to the ngModelController
which is only (I could be wrong here) available to the postLink
function.
Both the Controller
and Link
functions have access to the same scope (in this case, it is not always true) so I can do something like:
.directive('myDirective', [function() {
return {
....
controller: function ($scope, $element, $attrs) {
this.select = function (selected) {
$scope.ngModelCtrl.$setViewValue(selected);
};
},
link: function (scope, elem, attrs, ngModelCtrl) {
scope.ngModelCtrl = ngModelCtrl;
}
};
}])
.directive('myChildDirective', [function () {
return {
require: '^myDirective',
....
link: function (scope, elem, attrs, myDirectiveCtrl) {
elem.bind('click', function () {
myDirectiveCtrl.select(scope.value);
});
}
}
}]);
By assigning the ngModelController
to the scope I can access it in a controller function method which in turn can be called by a child directive but this seems pretty hacky and there must be a better solution so any help would be much appreciated.
Please see my Plunkr here