gpt4 book ai didi

javascript - 为什么简单地使用 ng-init 和 delete 会产生语法错误?

转载 作者:行者123 更新时间:2023-11-28 01:41:00 25 4
gpt4 key购买 nike

这个简单的片段(jsfiddle):

<div ng-app="App" ng-init="foo={a: 20}; delete foo['a']">
</div>

创建此syntax error在 FF 和 Chrome 中。为什么?

Syntax Error: Token 'foo' is an unexpected token at column 21 of the expression [foo={a: 20}; delete foo['a']] starting at [foo['a']].

无论我尝试delete foo['a']还是delete foo.a都没有关系 - 两者都可以在vanilla javascript中工作;在 ng-init 中都不起作用。

最佳答案

嗯,显然ngInit想要一个expression ,它是 AngularJS 解析器可以理解的 JS 子集。

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by the $parse service. Expressions are often post processed using filters to create a more user-friendly format.

It might be tempting to think of Angular view expressions as JavaScript expressions, but that is not entirely correct, since Angular does not use a JavaScript eval() to evaluate expressions.

(强调我的)

因此$parse不支持delete

另外,ngInit 文档说:

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

关于javascript - 为什么简单地使用 ng-init 和 delete 会产生语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20928202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com