angularjs中`value`属性和`ng-value`属性有什么区别 [英] What is the difference between `value` attribute and `ng-value` attributes in angularjs

查看:39
本文介绍了angularjs中`value`属性和`ng-value`属性有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

angularjs 模板中的 valueng-value 属性有什么区别?如果我在使用 value 属性的字段上使用 ng-if 它可以正常工作,但是如果我将属性 value 更改为 ng-value 它停止工作.

example 1//它有效<input type='radio' ng-model='difficulty' value='hard'/><div ng-if="难度=='困难'"><p>难度很大</p>

示例 2//它不起作用<input type='radio' ng-model='level' ng-value='hard'/><div ng-if="level == 'hard'" ><p>级别很难</p>

解决方案

根据 the docs, ngValue 采用一个 " 角度表达式,其值将绑定到 value 属性输入元素".

因此,当您使用 ng-value="hard" 时,它被解释为一个表达式,并且 value 绑定到 $scope.hard(可能是 undefined).
ngValue 对计算表达式很有用 - 在设置硬编码值时它没有 value 的优势.但是,如果您想使用 ngValue 对值进行硬编码,则必须将其括在 '' 中:

ng-value="'hard'"

<小时>

更新:
从 v1.6 开始,ngValue 还将设置元素的 value property(除了 value属性).它可能不会影响您的用例,但这是另一个值得记住的差异.

What is the difference between value and ng-value attributes in angularjs templates? If I use ng-if on the field using value attribute it works properly but if I change the attribute value to ng-value it stops working.

example 1  // it works 

<input type='radio' ng-model='difficulty' value='hard'/>
<div ng-if="difficulty == 'hard'">
     <p>difficulty is hard</p>
</div>  

Example 2 // it doesn't work

<input type='radio' ng-model='level' ng-value='hard'/>
<div ng-if= "level == 'hard'" >
     <p>level is hard</p>
</div>

解决方案

According to the docs, ngValue takes an "angular expression, whose value will be bound to the value attribute of the input element".

So, when you use ng-value="hard", it is interpreted as an expression and the value is bound to $scope.hard (which is probably undefined).
ngValue is useful for evaluating expressions - it has no advantage over value for setting hard-coded values. Yet, if you want to hard-code a value with ngValue, you must enclose it in '':

ng-value="'hard'"


UPDATE:
Starting with v1.6, ngValue will also set the value property of the element (in addition to the value attribute). It might not affect your usecase, but it's another difference worth keeping in mind.

这篇关于angularjs中`value`属性和`ng-value`属性有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆