Vikas
Vikas

Reputation: 138

angular two way function binding best practice

My requirement is to call child directive function from parent directive. Currently we have implemented publish-subscribe pattern. Child directive subscribe for some event and we make a trigger on parent directive. publish subscribe is implemented through $.callbacks

Other ways this can be done is using broadcast. Or a child directive have a watch on some variable and we can change this variable on parent.

We did not use broadcast because parent directive contains lot of child events and we did not want it to go through all.

There is another way we can implement this is using two way function binding

directives.directive('twoWayBind', function () {
    return {
        restrict: "E",
        transclude: true,
        templateUrl: 'app/twoWayBindFunction.html',
        scope: {
            twoWayBinding: '='
        },
        controller: 'twoWayBindFunctionController',
        bindAsController: true,
        controllerAs: 'vm',
        link: function (scope, element, attrs, controller) {
        }
    };
});


controllers.controller('twoWayBindFunctionController', ['$scope', function (scope) {
    var vm = this;
    vm.scope = scope;

    scope.twoWayBinding = function () {
        console.log('twoway bind');
    }    
}]);

we can call twoWayBinding function from parent scope.

I would like to understand what is the best practice.

Upvotes: 0

Views: 1954

Answers (1)

e.s
e.s

Reputation: 224

I found the best way for me is to pass an object from the parent directive to the child. Adding functions in the child directive to that object and call it from the parent.

app.directive('parent', function() {
    return {
        restrict: 'E',
        scope: {
            buttonCaption: '@'
        },
        bindToController : true,
        controllerAs : 'vm',
        template: "<button ng-click='vm.twoWayObject.childFunc()'>{{vm.buttonCaption}}</button><child two-way-obj='vm.twoWayObject'></child>",
        controller: function($scope) {  
            var vm = this;      
            vm.twoWayObject = {};
        },

        link: function() {             
        }   
    }
});

app.directive('child', function() {
    return {
        restrict: 'E',
        scope: {
            twoWayObj: '='
        },
        bindToController : true,
        controllerAs : 'vm',
        template: "<h1>Chuchi</h1>",             
        link: function() {             
        },
        controller: function($scope){
            var vm = this;
            vm.twoWayObj.childFunc = function(){
                alert('child function called');
            }
        }
    }
});

A add a Fiddle with an example.

Look at this question (the first answer):

How to call a method defined in an AngularJS directive?

Upvotes: 1

Related Questions