Find another element with the same directive within the same scope?

Is there a way to find another element with the same directive applied within the same scope?

I want to use this information to create a directive matching input values

.

eg. I may have a template with multiple inputs that use the same directive:

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

      

Primarily I would use this to compare password and password, but I would like to make this a more general directive.

+3


source to share


1 answer


You can create a parent directive and communicate between children and parents through a controller, or create a service to be shared between instances.

Another option is to provide generic data and functionality when declaring a directive, for example:



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 are multiple instances of a directive, but there is only one instance of a directive declaration (the function itself). The announcement is generic and therefore sameValueInstances

are generic. When angular instantiates the directive, it will create a new scope and execute the link function. Each instance gets its own scope, so we put scopes into instances. We then use whatever data we add to the scope to identify instances and can use communication functions to communicate.

+2


source







All Articles