EricC
EricC

Reputation: 5870

Get transcluded text in directives controller

I can get some text from my directive into my directives controller like this:

The html:

<my-directive text="Some text"></my-directive>

In the directive, I can get hold of the text like this:

bindToController: {
  text: "@"
};

And I could use it like this in the directive's controller:

controller: function() {
  this.textUpperCase = this.text.toUpperCase();
}

But how could can I get hold of the text in the directives controller via transclusion? So that I can have the html like this:

<my-directive>Some text</my-directive>

Upvotes: 1

Views: 1814

Answers (1)

AWolf
AWolf

Reputation: 8980

As mentioned in the comments you could use element.html() or transclusion.

But I would prefer transclusion because that's easier to work with the data. You can use $transclude in your controller or transcludeFn in compile or link method.

Here I think the best would be the controller.

Please have a look at this fiddle or the demo below.

I think injecting the $element into controller won't work becasue you would get the uncompiled template with-out the data you're looking for.

angular.module('demoApp', [])
.controller('mainCtrl', function($scope) {
    $scope.hello = 'hello world from scope';
})
.directive('upperCase', function() {
    return {
        restrict: 'E',
        transclude: true,
        scope: {
        },
        template: '<div>{{text}}</div>',
        controller: function($scope, $transclude, $element) {
            $transclude(function(clone, scope) {
                //console.log(clone.text(), scope.hello);
                console.log(clone);
                $scope.text = clone.text().toUpperCase();
                //transcludedContent = clone;
                //transclusionScope = scope;
            });
            //console.log($element.html()); // not working will get the uncompiled template from directive
            console.log($scope.text); // can be used here too
        },
        link: function(scope, element, attrs, ctrl, transclude) {
            var text = element.html();
            //console.log(transclude);
            //element.html(text.toUpperCase()); // also working (add ng-transclude to your template)
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainCtrl">
    <upper-case>hello world</upper-case>
    <upper-case>hello angular</upper-case>
</div>

Upvotes: 2

Related Questions