Wednesday, March 30, 2016

Angular JS Two way data binding

In this step, application will control the order in which the items are listed. Dynamic ordering is implemented by creating new model property, wiring it with the repeater, and letting the data binging magic do the rest of the work. 

w.r.to UI, application now also displays a drop down box which lets the user control the order in which the items are listed. 

template looks like the below 

Search : input ng-model=“query”
Sort By: 
select ng-model=“orderProp”
option value=“name” Alphabetical /option
option value=“age” Newest /option
select 

ul class=“phones” 
li ng-repeat=“phone in phones| filter:query | orderBy:orderProp”
span {{phone.name}} /span
span {{phone.snippet}} /span

/li
/ul

Angular creates data binding between the select element and the orderProp model. orderProp is then used as input for orderBy filter. 

below is how the controller looks like 

var phonecatApp = angular.module(‘phonecatApp’,[]);

phonecatApp.controller = (‘phoneListControl’, function($scope)
{
$scope.phones = [
{‘name’ : ‘Nexus S’, ‘snippet’ : ‘Fast got furious’ , ‘age’ : 1},
{‘name’ : ‘MOto S’, ‘snippet’ : ‘Fast got furious Moto’ , ‘age’ : 2},
{‘name’ : ‘Droid S’, ‘snippet’ : ‘Fast got furious Droid’ , ‘age’ : 3},

];
$scope.orderProp = ‘age’;
}

Notice that when the app is loaded in the browser, "Newest" is selected in the drop down menu. This is because we set orderProp to 'age' in the controller. So the binding works in the direction from our model to the UI. Now if you select "Alphabetically" in the drop down menu, the model will be updated as well and the phones will be reordered. That is the data-binding doing its job in the opposite direction — from the UI to the model.

References:

No comments:

Post a Comment