简体   繁体   中英

Multiple Parent Directive Instances

I am trying to create a pair of directives with a parent child relationship. I found that '^require' works well for this but the issue is I would like to have multiple instances of the directives on the page at the same time and can't figure out how to tell the child directives which parent directive is their parent.

An example would be using directive A as the parent and B as the child. If I add require A to directive B it knows that A is it's parent. However if I have A1, A2, B1 and B2 the B directives are still the child of the A directives but I can't specify that the instance of A with id A1 is the parent of B with id B1 like wise A2 is the parent of B2.

Maybe I'm making this too complicated or just going in the wrong direction. As always any idea's or tips are appreciated.

Here are two ideas:

1) Directives can share scope with the view's controller. So, you could implement the parent/child relationships in your controller and have the directives reflect the controller's state. There are several down sides to this approach: it tightly binds your directive to the controller and makes it difficult to use the same directive multiple times on the same page. These downers are a large impediment to reuse!

2) Directives can leverage html templates which allow for a lot of expressiveness. So perhaps the parent/child relationship could be expressed within a single directive, like this:

myapp.directive('mydirective', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            parentData: '@',
            childData: '@'
        },
        template:
            '<div ng-model={{parentData}}>' +
                '<div ng-model={{childData}}>' +
                '</div>' +
            '</div>',

        link: function (scope, element, attrs) {
            //other behaviors go here
        }
    }
});

Each instance of the above directive can have its unique parent and child binding via an isolate scope so it could be used across multiple controllers/views. The template above can be as complex as you need it to be. If the template gets much more complex than this, best practice is to load it from a separate html file.
Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM