Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  147] [ 3]  / answers: 1 / hits: 28060  / 10 Years ago, mon, may 26, 2014, 12:00:00

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>

More From » angularjs

 Answers
32

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.


[#70849] Friday, May 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
walker

Total Points: 726
Total Questions: 91
Total Answers: 106

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;