1

I am trying to use $parse to get my required result.

Here is my Example. Check script.js file

I want to parse an expression but I am getting error. How can I solve this kind of data?

Here is my code

    scope.data = {name:{_en:"username", _ar:'مفقود '}}

    // set variable in scope like scope.name_en = scope.data._en, scope.name_ar = scope.data._ar

    for(var i in scope.data) for(var j in scope.data[i]) scope[i+j] = scope.data[i][j];
    scope.messages2 = [{code:200, msg_en:"{{name_en}} is missing.", msg_ar:"مفقود {{name_ar}}"}];
    scope.finalMegs = [];

    for( var i in scope.messages2) {
      var obj = {};

      for(var j in scope.messages2[i]){
        if(j == 'code') continue;
        console.log(scope.$eval(scope.messages2[i][j]) );
        obj[j] = $parse(scope.messages2[i][j])
      }
      /*
      required object is {msg_en = "username is missing.", msg_ar:"مفقود مفقود "}
      */
      scope.finalMegs.push(obj);
    }
    console.log(scope.finalMegs);

Thank you.

1 Answer 1

1

Syntax of your messages is incorrect, so the messages can't be parsed by $parse or $eval. You should write them in this format:

scope.messages2 = [
   {
      code:200, 
      msg_en:"name_en + ' is missing.'", 
      msg_ar:"'مفقود ' + name_ar"
   }
];

Then if you want to get object with already formatted messages you should call $parse function in this way:

obj[j] = $parse(scope.messages2[i][j])(scope);

Because $parse converts angular expression to function, which you should call with your scope to get expected results.

But in your case, I think that you can replace those line to this also:

obj[j] = scope.$eval(scope.messages2[i][j]);

Result will be the same.

Example on plunker. (I've reformatted your example a little bit)


Please, take a look also at the example of usage scope.$eval here and documentation about $parse.

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

2 Comments

Is there any way to execute that message ? Because then i have to update a lot of messages. Thank you
I don't think so. Imagine, that your original message already wrapped in double curly brackets and it looks like this: "{{{{name_en}} is missing.}}" when you pass it to $eval function or $parse service. It's just incorrect syntax. You can easily test it by adding this line to your html and you'll see, that it produces the same errors. If you have any questions, let me know!

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.