问题
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.
回答1:
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>
回答2:
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 }}`
});
}
回答3:
Create a custom filter that can interpolate values within the current scope.
In your template: (this
refers to the current scope)
{{ b | interpolate:this }}
The filter implementation is trivial:
app.filter('interpolate', function($interpolate) {
return function(expression, context) {
return $interpolate(expression)(context);
};
});
Working example: http://jsbin.com/gegeji/1/edit?html,js,output
来源:https://stackoverflow.com/questions/17945800/double-indirection-in-data-binding-interpolate-string-in-a-template