【问题标题】:Accessing angular directive (element)'s text inside the template访问模板内的角度指令(元素)的文本
【发布时间】:2013-04-20 00:23:00
【问题描述】:

所以我在自定义组件上关注this EggHead.io tutorial,我遇到了这个问题。声明指令时,例如:

angular.module('myApp', [])
    .directive('myDir', function(){
        return {
            restrict: "E",
            controller: "myController",
            link: function(scope, element, attrs) {
                scope.foo = element.text();
            },
            templateUrl: "myDirTemplate.html"
        }
    });

模板是:

<div>The value is: {{foo}}</div>

以及正在使用的指令如下:

<html>
...
<myDir>Bar</myDir> 
...
</html>
链接函数中的

元素指的是

<div>The value is: {{foo}}</div>

在模板中。如果我不指定templateUrl,那么element指的是

<myDir>Bar</myDir> 

在主视图中,这是我想要的。我希望指令将“Bar”文本插入到 {{foo}} 中,最终结果为:

<div>The value is: Bar</div> 

但我不知道如何绕过每次选择模板元素的角度。

有什么想法吗?

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    你需要使用ngTransclude:

    app.directive('myDir', function(){
      return {
        restrict: "E",
        transclude: true,
        templateUrl: "myDirTemplate.html",
        replace: true
      }
    });
    

    然后你的外部模板变成类似于:

    <div>The value is: <span ng-transclude></span></div>
    

    在此处查看代码:http://plnkr.co/edit/EuT5UlgyxgM8d54pTpOr?p=preview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 2021-05-28
      • 1970-01-01
      • 2013-11-25
      相关资源
      最近更新 更多