Angular.js:如何$ EVAL工作,为什么它香草的eval有什么不同? [英] Angular.js: How does $eval work and why is it different from vanilla eval?

查看:145
本文介绍了Angular.js:如何$ EVAL工作,为什么它香草的eval有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇 $范围。$ EVAL 你这样经常在指令看,所以我检查了来源,发现在以下rootScope.js

  $ eval:评估函数(表达式,当地人){
    返回$解析(表达式)(这一点,当地人);
  },

$解析似乎是由 ParseProvider parse.js ,这似乎是确定某种自己的迷你语法(该文件是900线长)。

我的问题是:


  1. 到底是什么 $ EVAL 在做什么?为什么它需要自己的迷你解析语言?


  2. 为什么不是普通的旧的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 in rootScope.js:

  $eval: function(expr, locals) {
    return $parse(expr)(this, locals);
  },

$parse appears to be defined by ParseProvider in parse.js, which appears to define some kind of mini-syntax of its own (the file is 900 lines long).

My questions are:

  1. What exactly is $eval doing? Why does it need its own mini parsing language?

  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆