lharby lharby - 2 months ago 14
JSON Question

Move expression from template to controller

I have the following controller

.controller('retrieveSummaryData', [ '$scope', '$http', '$log', function ($scope, $http, $log) {
$scope.url = 'data/sub1_example.json';
$scope.search = function(){
angular.element('body').addClass('loading');
$scope.total = 0; // reset the scope total
$http.get($scope.url) // get json data
.success(function(data, status, headers, config) {
$scope.dataList = data;
angular.element('.downloadFile').removeClass('disabled');
angular.element('.colHeader').removeClass('hidden');
angular.element('body').removeClass('loading');
console.log(data);
}).error(function(error, status, headers, config) {
console.log(status);
});
}

}])


And in my template I have the following:

<li ng-repeat="data in dataList" class="outputData">
<ul class="clearfix">
....
<li class="col-md-1 sign">{{data.signage}}</li>
<li class="col-md-1 sign" ng-class="{valid: data.signage == '+-' || data.balance > 0 && data.signage == '+', invalid: data.balance < 0 && data.signage == '+' // etc}"></li>
</ul>
</li>


I want to move this expression to my controller. But my json is an array of objects.

How to iterate over these. In vanilla js I would just write a loop, but I assume angular has some built in function to do this?

Here is what I tried:

$scope.dataList = data;
$scope.signage = $scope.dataList.signage // undefined
$scope.returnClass(function(){
return {
valid: $scope.signage == '+' || $scope.signage == '+-',
invalid: $scope.signage == '-' // etc
}
}


If I do
$scope.dataList[0].signage
, I get the first item in the array. do I need to write a loop here?

Example of part of my json

[
{
"entity":"C-2919",
"entity_desc":"A & L CF June (3) Limited",
"account":"S1710008",
"account":"9706250",
"account_desc":"CT asset CY tfr group relief",
"l700_code":"R001000",
"l700_acc_desc":"S1710008 Corporation tax current yr - group relief settlemen",
"signage":"-",
"balance":0.00
},
{
"entity":"C-2919",
"entity_desc":"A & L CF June (3) Limited",
"account":"S1710010",
"walker_account":"9706204",
"walker_account_desc":"CORP TAX PY - B/F",
"l700_code":"R001004",
"l700_acc_desc":"S1710010 Corporation tax prior year - b/f",
"signage":"+",
"balance":376949.00
}, // etc

Answer

You can add function to return the boolean value

$scope.validQuery = function (data) {
  return (data.signage === '+-' || data.balance > 0 && data.signage ==   '+');
}
 $scope.invalidQuery = function (data) {
   return (data.signage === '-' && data.balance < 0);
}

ng-class can be written

ng-class="{valid: validQuery(data), invalid: invalidQuery(data)}"