javascript - Get children attributes in a directive - Stack Overflow

Given<mytag class="red"><mysubtag id="3"><mysubtag><mysubta

Given

<mytag class="red">
     <mysubtag id="3"></mysubtag>
</mysubtag> 

subtag might have different meanings depending on the parent tag (it might be mytag or mysupercustomtag). I have directives for all parent tags. How can I access the subtags?

I know in the link function of the directive for mytag I can use children(), contents(), and data(), and even elm.find('#someid'). Would something like the following do the trick? What's the correct way of doing that? nested directives?

.directive('mytag', function() {
  return {
    restrict: 'A',
    template: '<div></div>',
    replace: true,
    link: function (scope, element, attrs) {
        // get the id of the first child (for example mysubtag)
        var newid = element.children()[0].getAttribute('id');
        // and put it in mytag, so that it is transformed into <div class="red" id="3">..
        attrs.$set('id', newid);
    }
  } 
})

Given

<mytag class="red">
     <mysubtag id="3"></mysubtag>
</mysubtag> 

subtag might have different meanings depending on the parent tag (it might be mytag or mysupercustomtag). I have directives for all parent tags. How can I access the subtags?

I know in the link function of the directive for mytag I can use children(), contents(), and data(), and even elm.find('#someid'). Would something like the following do the trick? What's the correct way of doing that? nested directives?

.directive('mytag', function() {
  return {
    restrict: 'A',
    template: '<div></div>',
    replace: true,
    link: function (scope, element, attrs) {
        // get the id of the first child (for example mysubtag)
        var newid = element.children()[0].getAttribute('id');
        // and put it in mytag, so that it is transformed into <div class="red" id="3">..
        attrs.$set('id', newid);
    }
  } 
})
Share Improve this question edited Aug 25, 2013 at 15:54 Eduard Gamonal asked Apr 17, 2013 at 10:46 Eduard GamonalEduard Gamonal 8,0315 gold badges43 silver badges48 bronze badges 2
  • I think as per angularjs, parents are not suppose to know about children – Arun P Johny Commented Apr 17, 2013 at 11:32
  • 1 By the time the linking function runs, mysubtag is gone, since your directive has a template and uses replace: true. – Mark Rajcok Commented Apr 17, 2013 at 15:50
Add a ment  | 

1 Answer 1

Reset to default 5

This approach is not correct . For Nested directives you have to declare controller in parent directive and use require attribute in child directive to access parent controller.Please see below example from angular documentation for child parent directives. Below link will help you to set up one

http://angularjs/#create-ponents

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745352867a4623941.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信