Angular.js:如何$ EVAL工作,为什么它香草的eval有什么不同? [英] Angular.js: How does $eval work and why is it different from vanilla eval?
问题描述
我很好奇 $范围。$ EVAL
你这样经常在指令看,所以我检查了来源,发现在以下rootScope.js
:
$ eval:评估函数(表达式,当地人){
返回$解析(表达式)(这一点,当地人);
},
$解析
似乎是由 ParseProvider
在 parse.js $定义C $ C>,这似乎是确定某种自己的迷你语法(该文件是900线长)。
我的问题是:
-
到底是什么
$ EVAL
在做什么?为什么它需要自己的迷你解析语言? -
为什么不是普通的旧的JavaScript
评估
被使用?
$ EVAL
和 $解析
别ŧ评估JavaScript的;他们评估AngularJS 前pressions 的。链接的文档解释了前pressions和JavaScript之间的差异。
问:究竟是什么$ EVAL做什么?为什么它需要自己的迷你解析语言?
从文档:
防爆pressions是JavaScript的类code片段,通常都放在绑定,例如{{EX pression}}。防爆pressions由$解析服务处理。
块引用>这样的JavaScript一个小型的语言,它限制了可以运行(例如,没有控制流语句,除三元运算符),以及增加了一些AngularJS善良(例如过滤器)。
问:为什么不使用普通的旧的javascript的eval
由于它不是真正的JavaScript评估。由于文档说:
如果......你想运行任意JavaScript code,你应该让一个控制器方法并调用该方法。如果你想给eval()从JavaScript的角度前pression,使用$ eval()方法。
块引用>链接到上面的文档有很多的更多信息。
I was curious about the
$scope.$eval
you so often see in directives, so I checked out the source and found the following inrootScope.js
:$eval: function(expr, locals) { return $parse(expr)(this, locals); },
$parse
appears to be defined byParseProvider
inparse.js
, which appears to define some kind of mini-syntax of its own (the file is 900 lines long).My questions are:
What exactly is
$eval
doing? Why does it need its own mini parsing language?Why isn't plain old JavaScript
eval
being used?
解决方案
$eval
and$parse
don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.Q: What exactly is $eval doing? Why does it need its own mini parsing language?
From the docs:
Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.
It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).
Q: Why isn't plain old javascript "eval" being used?
Because it's not actually evaluating JavaScript. As the docs say:
If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.
The docs linked to above have a lot more information.
这篇关于Angular.js:如何$ EVAL工作,为什么它香草的eval有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!