What is the difference between `value` attribute and `ng-value` attributes in angularjs
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.
Comments
-
Sarfraz Ahmad almost 2 years
What is the difference between
value
andng-value
attributes in angularjs templates? If I useng-if
on the field using value attribute it works properly but if I change the attributevalue
tong-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>
-
Sarfraz Ahmad almost 10 yearsOkay, means when i type
ng-value='hard'
it will search$scope.hard
but when i type `value='hard' it will assign the value 'hard' to that field. thank you -
lvarayut over 9 yearsHow about
ng-value=false
? In this case, it is interpreted as stringfalse
instead ofscope.false
. -
gkalpak over 9 yearsIt is interpreted as boolean false and converted to string when assigning to the attribute
value
. It depends on how Angular's parser works. -
Marcus Junius Brutus over 8 years@ExpertSystem so how would
ng-value="someExpression"
be different from the simpler:value={{someExpression}}
? -
gkalpak over 8 years@MarcusJuniusBrutus: Most of the time it won't (there are some very subtle differences, which are really out of scope here). But then again, I would argue that
ng-value="someExpr"
is simpler thanvalue="{{ someExpr }}"
. Basically, I would usengValue
whenever I have an expression to evaluate andvalue
when the value is constant. -
Tamas almost 8 years@ExpertSystem , here is the difference which I found: adding an
<option>
withng-value
attribute will not work well if we intend to change the text in of the tag. Here is a plunker for demo: plnkr if you change ln#17 with html in ln#18 then it will work correctly. (the code was supposed to change the text of the html option from "All Venues" to "Reset Venues" and back) -
gkalpak almost 8 years@Tamas, both versions work for me. Note that this is a pretty old answer so things might change.