2
votes

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

1

1 Answers

0
votes

Maybe I don't quite understand what you are trying to accomplish, but why not just use ng-click on the element, and handle it in the parent controller completely?

And if you need to modify something from the parent scope, inject that object into the child scope.

http://plnkr.co/edit/w4AcNdWPOdVsfy0OmEc6?p=preview