Javascript 为什么我们需要 ng-click?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11902379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do we need ng-click?
提问by BanksySan
Angular apps use the ng-click()
attribute rather than the the onclick
event.
Angular 应用使用ng-click()
属性而不是onclick
事件。
Why is this?
为什么是这样?
采纳答案by groner
ng-click holds an angular expression. Angular expressions are evaluated in the context of an Angular scope, which is bound to the element having the ng-click attribute or an ancestor of that element.
ng-click 包含一个角度表达式。Angular 表达式在 Angular scope的上下文中计算,它绑定到具有 ng-click 属性的元素或该元素的祖先。
The Angular expression language doesn't include flow control statements and can't declare variables or define functions. These limitations mean templates can only access variables and run functions made available by a controller or directive.
Angular 表达式语言不包含流控制语句,不能声明变量或定义函数。这些限制意味着模板只能访问控制器或指令提供的变量和运行函数。
回答by rakslice
Angular doesn't change the meaning of the onclick
attribute; it adds the parallel ng-click
attribute to take an Angular expression. onclick
takes plain old JavaScript code even when you're using Angular.
Angular 不会改变onclick
属性的含义;它添加了 parallelng-click
属性以采用Angular 表达式。onclick
即使您使用的是 Angular,也使用普通的旧 JavaScript 代码。
Practically speaking, suppose what you're doing in a click handler is changing some variables in an Angular scope, or calling a function in an Angular scope that changes some variables.
To do that from JavaScript code (like what you would put in onclick
) requires a bunch of steps
实际上,假设您在单击处理程序中所做的是更改 Angular 作用域中的某些变量,或者调用 Angular 作用域中的函数来更改某些变量。要从 JavaScript 代码(如您将放入的内容onclick
)执行此操作,需要执行一系列步骤
- get a reference to the scope
- assign the variable or call the function
- call
scope.$apply
so that anything watching for updates to the variables that you changed gets notified
- 获取对范围的引用
- 分配变量或调用函数
- 调用
scope.$apply
以便通知任何监视您更改的变量更新的内容
This looks like:
这看起来像:
<a onclick="var $scope = angular.element(event.target).scope(); $scope.yourVar = 42; $scope.$apply()">Go</a>
and with ng-click
and an Angular expression for the assignment, almost all of that is implicit:
和ng-click
一个用于赋值的 Angular 表达式,几乎所有这些都是隐含的:
<a ng-click="yourVar = 42">Go</a>