Lazloman
Lazloman

Reputation: 1347

Communication between angularjs directives

I have a 'master' which uses templateUrl to specify which markup it should use. Within that template, I use 'rows' directive to layout div's in a view. Thus, the 'master' directive is a sort of parent to the 'rows'.

The 'rows' directive also uses templateUrl. The 'master' and 'rows' directives are re-used in many cases but I need to have the 'rows' directive layout its rows differently in each one. This prevents me from using attributes on the 'rows' directive since that would have a global affect.

I would like to add attributes on the 'master' directive and have those somehow pass-through to the 'rows' directive.

Is there a way I can accomplish this? I've seen an EggHead tutorial on inter-directive communication but that uses the 'child' directive as an attribute on the 'parent', which won't work for me.

I also read that I could use a service to communicate between the two but I'm unclear on how to do that. Angular's $broadcast might work, but given the number of rows, there could be a lot of that and if it's not serially done, my layout may suffer.

Upvotes: 0

Views: 283

Answers (1)

Enzey
Enzey

Reputation: 5254

Some would argue that you should use events but I think in your case directive level controllers to store data would be better. Since your row directive is dependent on your master directive you can use that to your advantage and store shared information in the master directive.

module.directive('masterDir', function() {
    return {
        // Requiring yourself makes 
        //   the directive level controller
        //   available in the link function
        require: 'masterDir',
        controller: function($scope) {
            // The return is needed to support Angular 1.2
            return this;
        },
        link: {
            pre: function(scope, element, attrs, masterDirCtrl) {
                masterDirCrtl.someAttribute = attrs.someAttributeFromTheDom;
            },
            post: function() {
            }
        }
    }
});


module.directive('rowDir', function() {
    return {
        require: 'masterDir',
        link: function(scope, element, attrs, masterDirCtrl) {
            var parentDirectiveAttr = masterDirCrtl.someAttribute;
        }
    }
});

Upvotes: 1

Related Questions