简体   繁体   中英

angularJs ng -Repeat over an array of json object

This is the format of json which I need to parse:

[{
  "perAddress": {
    "city": "Delhi",
    "Street": "saket",
    "pin": "101011"
  },
  "flag": false
}, {
  "perAddress": {
    "city": "Delhi",
    "Street": "malvya",
    "pin": "101011"
  },
  "flag": true,
  "alterAddress": {
    "city": "bangalore",
    "street": "velondore",
    "pin": "560103"
  }
}];
  1. If the flag is false then the corresponding row will not be highlighted and only perAddress will be populated .

  2. If the flag is true then the corresponding row will be highlighted with containing perAddress and on click on the row the alterAddress need to populated. How to iterate through the json?

Try this

 var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.data = [{ "perAddress": { "city": "Delhi", "Street": "saket", "pin": "101011" }, "flag": false }, { "perAddress": { "city": "Delhi", "Street": "malvya", "pin": "101011" }, "flag": true, "alterAddress": { "city": "bangalore", "street": "velondore", "pin": "560103" } }]; }); 
 .Highlight { background-color: yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <div ng-repeat="d in data" ng-init="" ng-click="d.flag = !d.flag" ng-class="{'Highlight' : d.alterAddress}"> <li>{{d.perAddress}} <div ng-if="d.alterAddress"> <div ng-if="!d.flag">{{d.alterAddress}}</div> </div> </li> </div> </div> 

Create a css class "Highlight" and use this code -

<ul>
  <li ng-repeat="i in jsonArray" ng-class="{'Highlight' : i.flag}">
    <span>{{i.perAddress.city}} | {{i.perAddress.Street}} | {{i.perAddress.pin}}</span>
  </li>
</ul>

I can tell you in 2 ways. No need of using flag too.

.highlight {
  background-color: gray;
}

Using flag solution follows:

 <div>
   <div ng-repeat="address in addresses" ng-class="{'highlight' : address.flag}">
    <a ng-if="!showAlterAddress" ng-click="showAlterAddress = !showAlterAddress">{{address.perAddress}}</a>
    <span ng-if="showAlterAddress">{{address.alterAddress}}</span>
   </div>
 </div>

Without using flag solution follows:

 <div>
   <div ng-repeat="address in addresses" ng-class="{'highlight' : address.alterAddress}">
    <a ng-if="!showAlterAddress" ng-click="showAlterAddress = !showAlterAddress">{{address.perAddress}}</a>
    <span ng-if="showAlterAddress">{{address.alterAddress}}</span>
   </div>
 </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM