【问题标题】:Include first child html in custom directive in AngularJS在AngularJS的自定义指令中包含第一个子html
【发布时间】:2014-07-07 09:57:01
【问题描述】:

我有一个 angularjs 指令,我为其加载了一个模板:

<div class="step" id="stepId" >
</div>

这是指令声明:

angular.module('PortfolioApp')
  .directive('slideStep', function () {
return {
    templateUrl: appUrl + '/templates/slideStep.html',
    restrict: 'E',
      link: function postLink(scope, element, attrs) {
        //element.text('this is the slideStep directive');
          console.log("element text" +element.text());
      },
    replace:true
};
});

我想要实现的是,我在使用指令时包含的 html 包含在替换的 html 中。例如:

<slide-step>
    <img src="images/HAC0.jpg"/>
</slide-step>

变成

<div class="step" id="stepId" >
   <img src="images/HAC0.jpg"/>
</div>

有没有一种方法可以简单地将元素的 HTML 的第一个子元素绑定到自定义元素?

【问题讨论】:

  • 我不明白你的问题是什么。 “[...] 元素 HTML 的第一个子元素与自定义元素的简单绑定”是什么意思?
  • 很抱歉不清楚。我的意思是“嵌入包含在使用该指令的 html 文件中的任何 html”。因此,如果我的指令内部有一些 html 元素,例如 some text 替换的 html 变为:
    一些文本

标签: javascript angularjs


【解决方案1】:

你需要使用transclusion:

https://docs.angularjs.org/api/ng/directive/ngTransclude

angular.module('PortfolioApp')
  .directive('slideStep', function () {
return {
    templateUrl: appUrl + '/templates/slideStep.html',
    restrict: 'E',
      link: function postLink(scope, element, attrs) {
        //element.text('this is the slideStep directive');
          console.log("element text" +element.text());
      },
    transclude:true,
};
});

在你的指令模板中:

<div class="step" id="stepId" ng-transclude>
</div>

【讨论】:

  • 谢谢,这正是我要找的,尽管我注意到尽管 html 是正确的,但使用 angular 生成的 html 的其他框架不起作用(在这种情况下印象深刻。 js) 可能是因为后者在 angular 还没有编译所有指令元素时搜索元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多