javascript 访问模板内的角度指令(元素)的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16115238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:19:22  来源:igfitidea点击:

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

javascriptangularjsangularjs-directive

提问by Rex T

So I am following this EggHead.io tutorialon custom components, and I came across this problem. When declaring a directive such as:

所以我正在关注这个关于自定义组件的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"
        }
    });

and the Template being:

模板是:

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

and the directive being used such as follows:

和使用的指令如下:

<html>
...
<myDir>Bar</myDir> 
...
</html>

elementin the link functionrefers to the

元件链接功能

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

in the template. If I don't specify the templateUrl, then elementrefers to the

在模板中。如果我不指定templateUrl,则元素指的是

<myDir>Bar</myDir> 

in the main view, which is what I want. I was hoping the directive would take the "Bar" text and insert it into the {{foo}}, giving the final result of:

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

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

But I don't know how to get around angular selecting the template's element every single time.

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

Any ideas?

有任何想法吗?

回答by JayQuerie.com

You need to use ngTransclude:

您需要使用ngTransclude

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

and then your external template becomes something similar to:

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

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

View the code working here: http://plnkr.co/edit/EuT5UlgyxgM8d54pTpOr?p=preview

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