In order to interpret the string, you need to interpolate it thanks to the angular's $interpolate
service.
Example:
link = (scope, element, attrs) =>
interpretedString = $interpolate(element.text())(scope)
Question
Is there a way to interpret the content of a div having my directive as an attribute :
example :
<div my-directive>{{1+1}}</div>
and my link function looks like this :
link = (scope, element, attrs) =>
interpretedString = element.text()
in this example interpretedString
is equal to {{1+1}}
instead of 2
any help? the scope.$eval
evaluates attributes, but what if I want to evaluate the text of a directive?
thanks
Solution
In order to interpret the string, you need to interpolate it thanks to the angular's $interpolate
service.
Example:
link = (scope, element, attrs) =>
interpretedString = $interpolate(element.text())(scope)
OTHER TIPS
Just to back up a bit, the contents of an element could be anything -- an array of element trees, text nodes, comments, and (unless you declare your directive "terminal") it all gets evaluated recursively and could have directives inside directive. I think you'd be much better off passing an interpolated string as an attribute. I mean you could do it this way, but whoever's using your widget wouldn't really expect that.
Something like:
<div my-directive my-attr="{{1+1}}"></div>
Or even (if that attribute is "primary"):
<div my-directive="{{1+1}}"></div>
From there, instead of $interpolate(element.text())(scope)
you'd have $interpolate(attrs.myDirective)(scope)
Of course, the nature of Angular is everything is dynamic and can update all the time. What if the expression didn't just have constants, as a real expression likely wouldn't. If it were:
{{1+foo}}
Then the question is do you care about it changing? If not, $interpolate is fine. It captures the initial value. If you do care about it updating, you should use $observe.
attrs.$observe('myDirective', function(val) {
// if say "foo" is 5, val would be 6 here
});
Then later if you're like scope.foo = 8
the callback runs and passes 9
.
Alternative is to do
<my-directive ng-bind="1+1" />
var two = $scope.$eval('ngBind');
:-p
.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
ngBind : '='
},
link: function (scope, element, attrs) {
console.log('expecting string "1+1": '+attrs.ngBind);
console.log('expecting evaluated string "2": '+scope.$eval('ngBind'));
}
};
});
side note: <div ng-bind="val"></div>
is almost the same as <div>{{val}}</div>
. Except that u save 4 brackets and never see them flashing into view when things might go slower whatsoever reason.