Double indirection in data-binding. Interpolate string in a template

我的梦境 提交于 2019-12-06 08:33:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!