最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing angular directive (element)'s text inside the template - Stack Overflow

programmeradmin3浏览0评论

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"
        }
    });

and the Template being:

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

and the directive being used such as follows:

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

element in the link function refers to the

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

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

<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.

Any ideas?

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"
        }
    });

and the Template being:

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

and the directive being used such as follows:

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

element in the link function refers to the

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

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

<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.

Any ideas?

Share Improve this question asked Apr 20, 2013 at 0:23 Rex TRex T 931 gold badge1 silver badge3 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 22

You need to use 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

发布评论

评论列表(0)

  1. 暂无评论