2

I have a controller like this:

function Ctrl( $scope ){

    $scope.str = " Misty Mountain Hop ";

}

And a view like this:

<div ng-controller="Ctrl">

    <p>{{ str }}</p>       <!-- This one is ok -->
    <p>{{ str.split( "Mountain")[0] }}</p>   <!--Even this one is fine too -->
    <p>{{ str.replace( /Mountain/ , "Plain" ) }}</p>  <!-- This one is bad -->

</div>

So if i try to use a replace method , it gives an error:

Syntax Error: Token 'Mountain' is unexpected ... 

http://jsfiddle.net/H3ztj/

The question is : Why?

9
  • 1
    How can I reproduce that in the fiddle you linked to? Clicking "Run" doesn't produce any error, it just prints the code (unreplaced). Commented Oct 6, 2013 at 12:03
  • You can work around it by using the RegExp constructor: str.replace(new RegExp('Mountain'), 'Plain'). Note that there are no delimiters, you need to double all backslashes and modifiers go in a second parameter see MDN Commented Oct 6, 2013 at 12:03
  • BTW, why do you try to do this logic in HTML? I think HTML represents View (MVC) only Commented Oct 6, 2013 at 12:14
  • @TimPietzcker in the console you can see the error Commented Oct 6, 2013 at 12:24
  • @MaximShoustin i have very specific use-case with my view , so i don't want to put this functionality in the scope.. Commented Oct 6, 2013 at 13:10

1 Answer 1

4

Since your question was "Why?", the answer is that expressions in interpolation blocks are not JavaScript expressions, but Angular expressions. They look a lot like JavaScript (on purpose), but Angular uses its own parser to parse the code.

That way it can do more than just evaluate the expression once: it can also do things like analyze the dependencies, so it can watch the ingredients and update when those ingredients change. It can also evaluate the expression relative to the $scope, so that {{foo}} returns $scope.foo rather than a global variable called foo (which in turn makes things like ngRepeat work).

When the Angular team implemented Angular expressions, they obviously didn't implement regular expressions. That's not surprising -- that kind of code should be in your controller anyway, where you can test it.

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

1 Comment

great , thanks! the reason it is not working is slashes in the replace(/Mountain/ , when this syntax is 100% works: replace("Mountain" , so seems like Angular team simply forgot to implement it :)

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.