<!DOCTYPE html>
<html ng-app="demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>
<script src="app.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="style.css" rel="stylesheet" />
<title></title>
</head>
<body class="container-fluid">
<div class="container">
<h3>Merged products ...</h3>
<div class="row" ng-controller="demoController">
<div class="row">
<div class="col-xs-6">
<table class="table table-condensed">
<tr>
<th>Brand</th>
<th>Unit</th>
<th>Price</th>
</tr>
<tr ng-repeat="p in _products">
<td>{{p.brand}}</td>
<td>{{p.unit}}</td>
<td>{{p.price}}</td>
</tr>
</table>
</div>
<div class="col-xs-6">
<pre>Products = {{_products | json}}</pre>
</div>
</div>
<hr />
</div>
</div>
</body>
</html>
angular.module('demo', []);
angular.module('demo').controller('demoController', ['$scope', '$q', '$log', '$timeout', function ($scope, $q, $log, $timeout) {
var vm = $scope;
// helper function to generate a list of product in a product data object
function generateMergeList(source) {
var result = [];
if (!source || !source.brands || !source.prices) {
return result;
}
var _brands = source.brands.split(',');
var _prices = source.prices.split(',');
if (_brands.length !== _prices.length) {
throw 'Number of items in brands and prices aren\'t the same...';
}
return _brands.map(function (elm, idx) {
return {
brand : elm,
price : _prices[idx],
unit : source.unit
};
});
}
// simulating a data service promise function ....
function _getProducts() {
var deferred = $q.defer();
var _result = [{
unit : '35 lb',
brands : 'CENTURY, BADGER',
prices : '65, 85'
}, {
unit : '45 lb',
brands : 'GOD KNOWS, JUST ANOTHER BRAND',
prices : '615, 1085'
}
];
$timeout(function () {
deferred.resolve(_result);
}, 1000);
return deferred.promise;
}
function onLoad() {
_getProducts().then(function (data) {
// flatten the prducts into one array ...
vm._products = data.reduce(function (previous, current) {
return previous.concat(generateMergeList(current))
}, []);
});
}
onLoad();
}
]);
/* Styles go here */
Stackoverflow | AngularJS mapping and flattening ...
Stackoverflow Link : http://stackoverflow.com/questions/34444021/split-and-map-array-from-comma-separated-string-list-in-angularjs
Helper References:
Array reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce