Eric B.
Eric B.

Reputation: 24411

How to double expand a variable name in AngularJS

Given an AngularJS template variables are automatically expanded by the framework when they are entered in the template.

Ex:

app.controller( "myCtrl", function($scope){
   $scope.myVar = "Some Text";
});

The following HTML will be properly expanded

<span>{{myVar}}</span>

to

<span>Some Text</span>

How do I get the template to accomplish this if I want to store the var name as part of my string instead:

app.controller( "myCtrl", function($scope){
   $scope.text = "This is quite {{myVar}}";
   $scope.myVar = "Some Text";
});

Unfortunately,

<span>{{myVar}}</span>

becomes

<span>This is quite {{myVar}}</span>

Is there any easy way to do this in the template? I've tried using the $interpolate service in the controller, but given that I'm passing scoped objects (from another closure) to the template, $interpolate updates the original object and causes me a problem. If there was an easy way to return an object by value (instead of by reference) it would solve my problems using $interpolate, but currently I can't figure out how to do that either.

Upvotes: 0

Views: 446

Answers (3)

V31
V31

Reputation: 7666

This can be done with the help of directive in this case. The trick is to use $compile service in this case.

I have created a plunker for the same.

Directive code:

app.directive('renderText',function($compile){
  var linker = function(scope,element,attr){
    var template = scope.item;
    scope.$watch('template',function(){
                element.html(template);
                $compile(element.contents())(scope);
            }); 
  }
  return {
    restrict: 'A',
    replace: true,
    link:linker,
    scope: { 
             item:'=item',
             myVar: '=replace'
            }
    };
});

Upvotes: 1

Eric B.
Eric B.

Reputation: 24411

I ended up using angular.copy to create a local copy of $scope.text such that any changes to it through the $interpolate service does not affect my original object.

Upvotes: 0

agconti
agconti

Reputation: 18093

How about this:

app.controller( "myCtrl", function($scope){
   $scope.myVar = "Some Text";
   $scope.text = "This is quite " + $scope.myVar;
});

Demo in a plunker: http://plnkr.co/edit/be374h7fXpY5YZjpe70n?p=preview

Upvotes: 1

Related Questions