Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `value` attribute and `ng-value` attributes in angularjs

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>
like image 278
Sarfraz Ahmad Avatar asked May 26 '14 08:05

Sarfraz Ahmad


People also ask

What is the difference between ngModel and ngValue?

Please note that 'ng-value' does have an advantage over hard-coding to the element attribute 'value', in that you can specify non-string types. For example, 'true' and 'false' will be stored to the model as booleans, rather than as strings. Also ngValue is a one-way binding, and ngModel is a two-way binding.

What is the difference between value and ngValue?

In Summary : Use [value] when you are binding to a string value and only a string value. Or you need access to the option value inside the HTML for automation purposes. Use [ngValue] when you are binding to any type and/or you want the entire option bound instead of just a string.

What is Ng value in angular?

The ng-value directive sets the value attribute of a input element, or a select element.


1 Answers

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.

like image 99
gkalpak Avatar answered Oct 08 '22 00:10

gkalpak