angular.formatter.index

Work in Progress This page is currently being revised. It might be incomplete or contain inaccuracies.

Description

Index formatter is meant to be used with select input widget. It is useful when one needs to select from a set of objects. To create pull-down one can iterate over the array of object to build the UI. However the value of the pull-down must be a string. This means that when on object is selected form the pull-down, the pull-down value is a string which needs to be converted back to an object. This conversion from string to on object is not possible, at best the converted object is a copy of the original object. To solve this issue we create a pull-down where the value strings are an index of the object in the array. When pull-down is selected the index can be used to look up the original user object.

Usage

In HTML Template Binding

<select name="bindExpression" ng:format="index:array">

In JavaScript

var userInputString = angular.formatter.index.format(modelValue, array);
var modelValue = angular.formatter.index.parse(userInputString, array);

Parameters

Returns

{object}

object which is located at the selected position.

Example

   <script>
   function DemoCntl(){
     this.users = [
       {name:'guest', password:'guest'},
       {name:'user', password:'123'},
       {name:'admin', password:'abc'}
     ];
   }
   </script>
   <div ng:controller="DemoCntl">
     User:
     <select name="currentUser" ng:format="index:users">
       <option ng:repeat="user in users" value="{{$index}}">{{user.name}}</option>
     </select>
     <select name="currentUser" ng:format="index:users">
       <option ng:repeat="user in users" value="{{$index}}">{{user.name}}</option>
     </select>
     user={{currentUser.name}}<br/>
     password={{currentUser.password}}<br/>
   it('should retrieve object by index', function(){
     expect(binding('currentUser.password')).toEqual('guest');
     select('currentUser').option('2');
     expect(binding('currentUser.password')).toEqual('abc');
   });