在视图中使用RegEx

在视图中使用RegEx

本文介绍了在视图中使用RegEx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的控制器:

I have a controller like this:

function Ctrl( $scope ){

    $scope.str = " Misty Mountain Hop ";

}

和这样的视图:

<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>

因此,如果我尝试使用 replace 方法,则会出现错误:

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

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

http://jsfiddle.net/H3ztj/

问题是:为什么?

推荐答案

由于您的问题是为什么?",因此答案是插值块中的表达式不是JavaScript表达式,而是角度表达式.它们看起来很像JavaScript(故意),但是Angular使用自己的解析器来解析代码.

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.

这样,它不仅可以对表达式进行一次评估:它还可以执行诸如分析依赖项之类的工作,因此它可以监视成分并在这些成分发生更改时进行更新.它还可以计算相对于 $ scope 的表达式,以便 {{foo}} 返回 $ scope.foo 而不是全局变量.称为 foo (依次使ngRepeat之类的东西起作用).

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).

当Angular团队实现Angular表达式时,他们显然没有实现正则表达式.这不足为奇-无论如何,这种代码都应该在您的控制器中,您可以在其中进行测试.

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.

这篇关于在视图中使用RegEx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:12