Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 951
Rex T Avatar asked Apr 20 '13 00:04

Rex T


1 Answers

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

like image 102
Jay Avatar answered Oct 25 '22 14:10

Jay