簡體   English   中英

訪問模板內的angular directive(element)文本

[英]Accessing angular directive (element)'s text inside the template

所以我遵循關於自定義組件的這個EggHead.io教程 ,我遇到了這個問題。 在聲明指令時,例如:

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>

link函數中的 元素指的是

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

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

<myDir>Bar</myDir> 

在主視圖中,這就是我想要的。 我希望該指令采用“Bar”文本並將其插入{{foo}},給出最終結果:

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

但我不知道如何繞過每次角度選擇模板的元素。

有任何想法嗎?

您需要使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM