Monday, 25 April 2016

How to use Arrays as data model ?


USING ARRAY AS DATA MODEL

Controller and data model (array) defined inside myapp.js
myapp.controller('moduleController1', function(){
   this.products = cars;
});

var cars = [
  {
    name: 'Swift',
    price: 750000,
    desc: 'Maruti Suzuki',
   purchasable: true
  },
  {
    name: 'Palio',
    price: 450000,
    desc: 'Fiat Palio',
    purchasable: false
  },
  ...
];


Accessing products array item in Web page
<body ng-controller="moduleController1 as c1">
    <div>
       <h1>{{c1.products[0].name}}</h1>
       <h1>{{c1.products[0].price}}</h1>
       <p>{{c1.products[0].desc}}</p>
       <button ng-show="c1.products[0].purchasable">Buy now</button>
    </div>
    ...
</body>


Iterating array in Web page using ng-repeat directive
<body ng-controller="moduleController1 as c1">
    <div ng-repeat="prd in c1.products">
       <h1>{{prd.name}}</h1>
       <h1>{{prd.price}}</h1>
       <p>{{prd.desc}}</p>
       <button ng-show="prd.purchasable">Buy now</button>
    </div>
    ...
</body>

No comments:

Post a Comment

Note: only a member of this blog may post a comment.