I'm trying to resolve double binding in the link function of a directive:
scope.a = "surprise";
scope.b = "{{ a }}";
the template is <div>{{ b }}</div>
it's rendered like <div>{{ a }}</div>
is it possible to get the view to display <div>surprise</div> ?
I've been trying to recompile the directive, but once b is binded, contents are a string and angularJS won't attempt any more to bind them.
One way is to interpolate on function rather then value directly
function test($scope) {
$scope.a = "surprise";
$scope.b = function () {
return $scope.a;
};
}
<div>{{ b() }}</div>
The original post is a simplification of my problem. Basically I had in the scope strings like {{ foo }} that had to be assigned to a variable in the template (for example, {{ b }} in the post), because the value is different depending on certain factors.
As @AjayBeniwal mentioned, a simple case is solved with a function. This is basically the same as
function test($scope) {
var foo = "surprise";
$scope.b = function () {
return foo;
};
}
but instead of foo, I got a property of the scope object and I interpolate on a function.
What I did instead is to watch for changes in the string. See directive not interpolating, in a template string
return {
template: '<div class="caption">{{ caption }}</div>',
link: function (scope, element, attrs) {
scope.caption = fooService.computeCaption(); // here caption is set to a string '{{ bar }}'
scope.$watch('caption', function(newValue) {
scope.caption = newValue;
$compile(element.contents())(scope); // resolve (interpolate?) the string `{{ bar }}`
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With