AngularJS: API: ng/directive/ngValue


ngValue

  1. - directive in module ng

Binds the given expression to the value of input[select] or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.

ngValue is useful when dynamically generating lists of radio buttons using ng-repeat, as shown below.

Directive Info

  • This directive executes at priority level 0.

Usage

  • as attribute:
    <input
      [ng-value=""]>
    ...
    </input>

Arguments

ParamTypeDetails
ngValue
(optional)
string

angular expression, whose value will be bound to the value attribute of the input element

Example

index.html
<script>
   angular.module('valueExample', [])
     .controller('ExampleController', ['$scope', function($scope) {
       $scope.names = ['pizza', 'unicorns', 'robots'];
       $scope.my = { favorite: 'unicorns' };
     }]);</script>
 <form ng-controller="ExampleController">
   <h2>Which is your favorite?</h2>
     <label ng-repeat="name in names" for="{{name}}">
       {{name}}
       <input type="radio"
              ng-model="my.favorite"
              ng-value="name"
              id="{{name}}"
              name="favorite">
     </label>
   <div>You chose {{my.favorite}}</div>
 </form>
protractor.js
var favorite = element(by.binding('my.favorite'));

it('should initialize to model', function() {
  expect(favorite.getText()).toContain('unicorns');});
it('should bind the values to the inputs', function() {
  element.all(by.model('my.favorite')).get(0).click();
  expect(favorite.getText()).toContain('pizza');});