简体   繁体   English

多个父指令实例

[英]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. 我发现'^ require'可以很好地解决这个问题,但是问题是我想同时在页面上拥有多个指令实例,并且不知道如何告诉子指令哪个父指令是其父指令。

An example would be using directive A as the parent and B as the child. 例如,将指令A用作父级,将B用作子级。 If I add require A to directive B it knows that A is it's parent. 如果我将要求A添加到指令B中,它将知道A是它的父级。 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. 但是,如果我有A1,A2,B1和B2,则B指令仍然是A指令的子代,但我无法指定ID为A1的A实例是ID为B1的B的父代,就像明智的A2是父代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. 1)指令可以与视图的控制器共享范围。 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. 2)指令可以利用html模板,这些模板具有很多表现力。 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. 如果模板比这复杂得多,则最佳实践是从单独的html文件中加载模板。
Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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