Iladarsda
Iladarsda

Reputation: 10696

Find other element with same directive within same scope?

Is there any way to find other element with same directive applied within same scope?

I want to use this info to create matching input values directive.

e.g. I might have a template with a few inputs which all using same directive:

<div ng-controller="MainCtrl">
    <input type="text" same-value>
    <input type="text" same-value>
</div>

Primarily I would use this for comparing password & password repeat, but I wanted to make this more general directive.

Upvotes: 3

Views: 546

Answers (1)

Samuel Neff
Samuel Neff

Reputation: 74909

You can create a parent directive and communicate between children and parent via the controller or you can create a service that is shared across instances.

Another option is to provide shared data and functionality when the directive is declared, as in:

angular.module("whatever").directive("sameValue", function() {

    var sameValueInstances = [];    

    return {
        link: function(scope, elem, attr) {
            sameValueInstances.push(scope);

            // register listener to remove from array when destroyed..


            // do something with the instance array
            sameValueInstances.forEach(...);
        }
    };

});

There is more than one instance of the directive, but there is only one instance of the declaration of the directive (the function itself). The declaration is shared and therefore sameValueInstances are shared. When angular instantiates a directive, it will create a new scope and cal the link function. Each instance gets its own scope, which is why we put the scopes on the instances. We then use whatever data we add to the scope to identify instances and can use functions on scope to communicate.

Upvotes: 2

Related Questions