2

Say I have an object such as:

obj = {foo: 42, bar: 'moo'}

And an interpolate string such as:

s = 'Do {{ bar }} {{ foo }} times.'

Interpolating this in Angular:

var interp = $interpolate(s);
var res = interp(obj);
console.log(res);  // <--- This will return 'Do moo 42 times.'

Is there a way I can express dotted/nested notation? Example:

obj = {n: {foo: 42}, bar: 'moo'}
s = 'Do {{ bar }} {{ n.foo }} times.'  // <--- This doesn't work

var interp = $interpolate(s);
var res = interp(obj);
console.log(res);
4
  • Your code work fine in jsfiddle. Try it jsfiddle.net/utnqdfwd Commented Mar 6, 2016 at 21:34
  • @DmitriyLoskutov Indeed, I got confused with my own code. Anyways, is there a way I could evaluate an already evaluaten interpolation? jsfiddle.net/utnqdfwd/2 Commented Mar 6, 2016 at 21:52
  • I mean, look at the fiddle I pasted. x is n.foo, but how can I reference the object itself so interpolating {{ x }} will actually return the value of obj.n.foo? Commented Mar 6, 2016 at 21:53
  • 1
    I guess jsfiddle.net/utnqdfwd/3. But I think it is not good :) Try to read more about it from docs.angularjs.org/api/ng/service/$interpolate Commented Mar 6, 2016 at 22:02

1 Answer 1

2

$parse service can solve your problem.

$parse service converts angular expression into a function.

You should convert expression n.foo to a function :

var parserFunc = $parse(obj.x)

Now, if you use parserFunc function with a parameter that you want to parse, it returns the value according to expression. Solution can be like:

var module = angular.module('name', []);

module.directive('app', ['$interpolate','$parse', function ($interpolate,$parse) {
    return {
    link: function () {
      var obj = {n: {foo: 42}, bar: 'moo', x: 'n.foo'};
      obj.parserFunc = $parse(obj.x);

      var s = 'Do {{ bar }} {{ parserFunc(this) }} times.';  // <--- x is 'n.foo'

      var interp = $interpolate(s);
      var res = interp(obj);
      console.log(res);
    }
  }
}]);

angular.bootstrap(document, ['name']);

Code work fine in jsfiddle.net/utnqdfwd/5/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.