访问角指令(元素)的模板内的文本 [英] Accessing angular directive (element)'s text inside the template

查看:134
本文介绍了访问角指令(元素)的模板内的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我下面的上的自定义组件此EggHead.io教程,我碰到这个问题来了。当声明指令如:

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

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>

和正在使用的指令,例如,如下所示:

and the directive being used such as follows:

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

元素的在链接功能的指

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

在模板中。如果我不指定的 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:

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

但我不知道如何解决的角度选择模板的元素每一次。

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

任何想法?

推荐答案

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

查看code在这里工作:<一href=\"http://plnkr.co/edit/EuT5UlgyxgM8d54pTpOr?p=$p$pview\">http://plnkr.co/edit/EuT5UlgyxgM8d54pTpOr?p=$p$pview

这篇关于访问角指令(元素)的模板内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆