0

I have the following sudo html

<foo>
    <span>Bar</span>
</foo>

and directive:

myapp.directive('foo', function () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: '<div><p>{{usedToBeInSpan}}</p></div>'
    }
});

How can I extract the contents of the nested span node and set its contents in the directives scope to usedToBeInSpan?

Note that I am not actually using this to replace a nested tag, it's just a simplified example

2
  • you have to create link function and extract all html content from span using .html() and add in your template Commented Feb 9, 2015 at 9:48
  • @ArpitSrivastava Thanks, see my question on @manasisakhare's answer... what do I use the .html() function on? Commented Feb 9, 2015 at 11:00

2 Answers 2

1

You can add a link function in your directive as below:

myapp.directive('foo', function () {
return {
    restrict: 'E',
    replace: true,
    transclude: true,
    template: '<div><p>{{usedToBeInSpan}}</p></div>',
    link: function (scope, element, attrs) {
           // the element argument contains the html content inside the directive tags <foo></foo>
          scope.usedToBeInSpan = "";//populate from "element"
    }
}
});
Sign up to request clarification or add additional context in comments.

4 Comments

That's exactly as far as I understand it. How do I access / populate the nested elements inside my directive?
you can use the traditional HTML Element methods which you can find under: w3schools.com/jsref/dom_obj_all.asp or w3schools.com/jsref/prop_node_childnodes.asp
in the link function, check the second argument it is an html "Element"
Right, but what that gives me is the html of the template, not the html of the nested nodes of my directive tag.
0

Found a new solution. Angular creates a css class named after the directive content, like "ng-<directive>-content" using this you can access the content of the directive where it was used. Have a look at this fiddle:

https://jsfiddle.net/manasisakhare/8ezh35to/2/

myapp.directive('foo', function () {
    return {
        restrict: 'E',
        //replace: true,
        transclude: true,
        template: '<div><p class="ng-foo-content" ng-transclude></p></div>'
    }
});

1 Comment

Thanks, this seems interesting. When I run the fiddle, the ´<foo>´ tag still wraps the correctly replaced content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.