【问题标题】:Access nested nodes in angular directive访问角度指令中的嵌套节点
【发布时间】:2015-02-09 09:43:34
【问题描述】:

我有以下 sudo html

<foo>
    <span>Bar</span>
</foo>

和指令:

myapp.directive('foo', function () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: '<div><p>{{usedToBeInSpan}}</p></div>'
    }
});

如何提取嵌套的span 节点的内容并将其在指令范围内的内容设置为usedToBeInSpan

请注意,我实际上并没有使用它来替换嵌套标签,它只是一个简化的示例

【问题讨论】:

  • 您必须创建link 函数并使用.html()span 中提取所有html 内容并添加到您的模板中
  • @ArpitSrivastava 谢谢,在@manasisakare 的回答中查看我的问题......我应该在什么上使用.html() 函数?

标签: javascript angularjs angular-directive


【解决方案1】:

您可以在指令中添加链接功能,如下所示:

myapp.directive('foo', function () {
return {
    restrict: 'E',
    replace: true,
    transclude: true,
    template: '<div><p>{{usedToBeInSpan}}</p></div>',
    link: function (scope, element, attrs) {
           // the element argument contains the html content inside the directive tags <foo></foo>
          scope.usedToBeInSpan = "";//populate from "element"
    }
}
});

【讨论】:

  • 据我所知完全是这样。如何访问/填充指令中的嵌套元素?
  • 您可以使用传统的 HTML Element 方法,您可以在以下位置找到:w3schools.com/jsref/dom_obj_all.aspw3schools.com/jsref/prop_node_childnodes.asp
  • 在链接函数中,检查第二个参数是一个html“元素”
  • 对,但是给我的是模板的html,而不是我的指令标签的嵌套节点的html。
【解决方案2】:

找到了一个新的解决方案。 Angular 创建一个以指令内容命名的 css 类,例如“ng--content”,使用它你可以访问使用它的指令的内容。看看这个小提琴:

https://jsfiddle.net/manasisakhare/8ezh35to/2/

myapp.directive('foo', function () {
    return {
        restrict: 'E',
        //replace: true,
        transclude: true,
        template: '<div><p class="ng-foo-content" ng-transclude></p></div>'
    }
});

【讨论】:

  • 谢谢,这看起来很有趣。当我运行小提琴时,“”标签仍然包裹着正确替换的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多