How to show json datasets in multiple divs - javascript

I have a scenario where I have to show json data in multiple divs. I am not sure how to do this. So far I was able to get the json data and print it in console.
Let's say I have six divs and each of them have the following fields:
DIV 1
----------------
| JName: value1 |
| JobSkill: value2 |
| Descrip : value3 |
| Salary: value4 |
| Experien: value5 |
----------------
DIV 2
----------------
| JName: value1 |
| JobSkill: value2 |
| Descrip : value3 |
| Salary: value4 |
| Experien: value5 |
----------------
I want to map each json dataset values to each div1, div2..etc
I have json like this:
{"jobName":"NASA Scientist","jobPrimarySkill":null,"jobRole":"JOB_ROLE","jobDesignation":"JOB_EXP","jobDescription":"JOB_DESCRIPTION","jobSalaryRange":"JOB_POSITIONS","jobExp":"JOB_SAL_RANGE","jobPositions":"JOB_POSTEDBY","jobPostedBy":null}
{"jobName":"NASA Scientist","jobPrimarySkill":null,"jobRole":"JOB_ROLE","jobDesignation":"JOB_EXP","jobDescription":"JOB_DESCRIPTION","jobSalaryRange":"JOB_POSITIONS","jobExp":"JOB_SAL_RANGE","jobPositions":"JOB_POSTEDBY","jobPostedBy":null}
{"jobName":"NASA Scientist","jobPrimarySkill":null,"jobRole":"JOB_ROLE","jobDesignation":"JOB_EXP","jobDescription":"JOB_DESCRIPTION","jobSalaryRange":"JOB_POSITIONS","jobExp":"JOB_SAL_RANGE","jobPositions":"JOB_POSTEDBY","jobPostedBy":null}
{"jobName":"NASA Scientist","jobPrimarySkill":null,"jobRole":"JOB_ROLE","jobDesignation":"JOB_EXP","jobDescription":"JOB_DESCRIPTION","jobSalaryRange":"JOB_POSITIONS","jobExp":"JOB_SAL_RANGE","jobPositions":"JOB_POSTEDBY","jobPostedBy":null}
{"jobName":"NASA Scientist","jobPrimarySkill":null,"jobRole":"JOB_ROLE","jobDesignation":"JOB_EXP","jobDescription":"JOB_DESCRIPTION","jobSalaryRange":"JOB_POSITIONS","jobExp":"JOB_SAL_RANGE","jobPositions":"JOB_POSTEDBY","jobPostedBy":null}
{"jobName":"NASA Scientist","jobPrimarySkill":null,"jobRole":"JOB_ROLE","jobDesignation":"JOB_EXP","jobDescription":"JOB_DESCRIPTION","jobSalaryRange":"JOB_POSITIONS","jobExp":"JOB_SAL_RANGE","jobPositions":"JOB_POSTEDBY","jobPostedBy":null}
so the first line or set of json should map to div1 and then the second one to div2 etc. How do I do this?
If I ng-repeat then it prints every thing in one div.
Html with six divs:
<div class="col-lg-8 col-md-6 col-sm-12">
<div class="job_box col-lg-offset-0" style="float: left; margin: 2px;" ng-controller="jobSummaryController">
<ul>
<li ng-repeat="x in token">
{{ x.jobName }}
</li>
</ul>
</div>
<div class="job_box col-lg-offset-0" style="float: left; margin: 2px;">Some text </div>
<div class="job_box col-lg-offset-0" style="float: left; margin: 2px;">Some text </div>
<div class="job_box col-lg-offset-0" style="float: left; margin: 2px;">Some text </div>
<div class="job_box col-lg-offset-0" style="float: left; margin: 2px;">Some text </div>
<div class="job_box col-lg-offset-0" style="float: left; margin: 2px;">Some text </div>
</div>
angular controller:
myApp.controller('jobSummaryController', function ($scope, $http) {
var url = 'rs/FetchJobSummary';
$http.get(url).success(function (response)
{
$scope.token = response;
console.log("job is:" + JSON.stringify(response));
}).error(function (response)
{
console.log("error", response);
});
});

the element you use ng-repeat on will be repeated as many times as there's items in your array/object.
So the way you got about it if you want 6 divs is you use ng-repeat on the div element you want to be repeated:
<div ng-repeat="x in token" class="job_box col-lg-offset-0" style="float: left; margin: 2px;">
<ul>
<li ng-bind="x.jobName">
</li>
<li ng-bind="x.jobPrimarySkill">
</li>
<!--...-->
<ul>
</div>

you have to put the ng-repeat on the div elements
http://plnkr.co/edit/TntCqHhbKDqaebDSlbOE?p=preview
<div ng-repeat="x in token" style="border:2px solid black;">
{{ x.jobName }}<br>
{{ x.jobPrimarySkill }}<br>
{{ x.jobRole }}<br>
{{ x.jobDesignation }}<br>
{{x.jobDescription}}<br>
</div>
if you want to use a directive
http://plnkr.co/edit/FWattoHd9yFmVbnCpUDC?p=preview
app.directive('mydir',function(){
return {
restrict: 'E',
scope : {
data : '='
},
templateUrl: 'mydir.html'
};
});
and html call
<div ng-repeat="data in token">
<mydir data='data'></mydir>
</div>
and the directive html :
<div style="border:2px solid black;margin:10px;">
{{data.jobName }}<br>
{{data.jobPrimarySkill }}<br>
{{data.jobRole }}<br>
{{data.jobDesignation }}<br>
{{data.jobDescription }}<br>
{{data.jobSalaryRange }}<br>
{{data.jobExp }}<br>
{{data.jobPositions }}<br>
{{data.jobPostedBy }}<br>
</div>

try
<div ng-controller="jobSummaryController">
<div class="job_box col-lg-offset-0" style="float: left; margin: 2px;"
ng-repeat="i in [1,2,3,4,5]">
<ul>
<li ng-bind="x.jobName"></li>
<li ng-bind="x.jobxxx"></li>
...
</ul>
</div>
</div>

Related

checking the condition in ng-repeat

I am creating app in ionic /angularjs.
The controller fetches the data in JSON format from the URL and displays unique images in div elements. I want to allow these images to be clicked and then display the data according to offer_name, which is coming from the JSON data.
e.g.: Suppose I display the image for Amazon (in background offer_name is amazon (having 10 records)). When the user clicks on that, it displays all the records related to amazon.
Hope you get my point but no database is included; it only works with JSON data.
Also, how can the check current value be checked in ng-repeat?
Here is my code:
.controller('menuCtrl', function($scope,$http) {
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
$scope.myData = response.data;
/* $scope.stack=[];
angular.forEach($scope.myData, function(item){
$scope.stack =item.store_image;
var uni_img=[];
for(var i=0 ; i< $scope.stack.length;i++)
{
if(uni_img.indexOf($scope.stack[i] == -1))
uni_img.push($scope.stack[i]);
}
console.log(uni_img);
})*/
});
$scope.dealopen = function($a){
for (var i=0;i<$scope.myData.length;i++)
{
//console.log($scope.data[i].name);
$link=$scope.data[i].offer_name;
if ($link==$a)
{
$window.open($link,"_self","location=yes");
console.log($a);
}
}
}
})
Html
<div class="item col-sm-2 col-sm-3 col-md-2 " ng-repeat="da in myData | unique: 'store_image'" >
<div class="thumbnail">
<img class="thumbnail img-responsive " ng-src="{{ da.store_image}}"
/>
<div class="caption">
<b class="group inner list-group-item-heading center-block">
{{da.offer_name | limitTo: 12 }} Deals</b>
<a class="item item-text-wrap" ng-href="#/Deals/{{da.offer_name}}">View Deal</a>
</div>
</div>
</div>
Here is the output:
.
One way to achieve this is to use ng-click to execute javascript (e.g. inline or call a function in the controller scope. Per the documentation for ngRepeat $index can be referenced for the current index:
Special properties are exposed on the local scope of each template instance, including:
+----------+---------+-----------------------------------------------------------------------------+
| Variable | Type | Details |
+----------+---------+-----------------------------------------------------------------------------+
| $index | number | iterator offset of the repeated element (0..length-1) |
| $first | boolean | true if the repeated element is first in the iterator. |
| $middle | boolean | true if the repeated element is between the first and last in the iterator. |
| $last | boolean | true if the repeated element is last in the iterator. |
| $even | boolean | true if the iterator position $index is even (otherwise false). |
| $odd | boolean | true if the iterator position $index is odd (otherwise false). |
+----------+---------+-----------------------------------------------------------------------------+
1
So the image tag can have the attribute ng-click to utilize that directive, like this:
<img class="thumbnail img-responsive " ng-src="{{ da.store_image}}" ng-click="showData(da.offer_name, $index)"/>
Then use Array.filter() to filter all offers into a filtered array of offers matching the offer_name:
$scope.showData = function (offer_name, index) {
$scope.offerName = da.offer_name;
$scope.filteredOffers = $scope.myData.filter(function(offer) {
return offer.offer_name == $scope.offerName;
});
}
And then add another set of elements to display the items in filteredOffers.
<div ng-repeat="offer in filteredOffers">
<div class="couponCode">{{offer.coupon_code}}</div>
<div class="couponTitle">{{offer.coupon_title}}</div>
<div class="couponDescription">{{offer.coupon_Description}}</div>
</div>
See the example below where the showData function updates the model selectedIndex, offerName and filteredOffers using these components.
angular.module('myApp', ['ui'])
.controller('menuCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.offerName = ''; //set initially
$scope.selectedIndex = -1;
$scope.filteredOffers = [];
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function(response) {
$scope.myData = response.data;
});
$scope.showData = function(offer_name, index) {
$scope.offerName = offer_name;
$scope.filteredOffers = $scope.myData.filter(function(offer) {
return offer.offer_name == $scope.offerName;
});
$scope.selectedIndex = index;
}
}
]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js" data-semver="1.1.5" data-require="angular.js#*" context="anonymous"></script>
<script data-require="angular-ui#*" data-semver="0.4.0" src="//rawgithub.com/angular-ui/angular-ui/master/build/angular-ui.js" context="anonymous"></script>
<div ng-app="myApp" ng-controller="menuCtrl">
<div>
OfferName:
<span ng-bind="offerName"></span>
</div>
<div>
selected index:
<span ng-bind="selectedIndex"></span>
</div>
<div class="item col-sm-2 col-sm-3 col-md-2 " ng-repeat="da in myData | unique: 'store_image'">
<div class="thumbnail">
<img class="thumbnail img-responsive " ng-src="{{ da.store_image}}" ng-click="showData(da.offer_name, $index)" />
<div class="caption">
<b class="group inner list-group-item-heading center-block">
{{da.offer_name | limitTo: 12 }} Deals</b>
<a class="item item-text-wrap" ng-href="#/Deals/{{da.offer_name}}">View Deal</a>
</div>
</div>
</div>
<div ng-repeat="offer in filteredOffers">
<div class="couponCode">{{offer.coupon_code}}</div>
<div class="couponTitle">{{offer.coupon_title}}</div>
<div class="couponDescription">{{offer.coupon_Description}}</div>
</div>
</div>
1 https://docs.angularjs.org/api/ng/directive/ngRepeat
You can use $index, that is the variable used in agular to know the index position in ng-repeat, if you want to know more about another contro variables of ng-repeat read the docs in the next link https://docs.angularjs.org/api/ng/directive/ngRepeat
An basic example is.
CONTROLLER
app.controller('menuCtrl', function($scope,$http) {
$scope.myData = [{path:'http://www.imagefree1.com',info:'http://www.infoimage1.com'},
{path:'http://www.imagefree2.com',info:'http://www.infoimage2.com'},
{path:'http://www.imagefree3.com',info:'http://www.infoimage3.com'}];
$scope.callDetail=function(index)
window.open(myData[index].info);
})
HTML
<div ng-repeat="image in myData">
<a href="#" ng-click="callDetail($index)">
<img src="image.path" alt="Description"/>
</a>
</div>
At first look you never call the $scope.dealopen function,
may be this can work....
<div class="item col-sm-2 col-sm-3 col-md-2 " ng-repeat="da in myData | unique: 'store_image'" >
<div class="thumbnail">
<img class="thumbnail img-responsive " ng-src="{{ da.store_image}}"/>
<div class="caption">
<b class="group inner list-group-item-heading center-block">{{da.offer_name | limitTo: 12 }} Deals</b>
<a class="item item-text-wrap" ng-click="dealopen(da.offer_name)">View Deal</a>
</div>
</div>
</div>

Angular - loop over nested javascript arrays

How can I use ng-repeat to loop over data that contains many nested array data?
I have data that will have many "Segments"
Example:
confirm.booking.flightData[0].Segments[0].FlightNumber
confirm.booking.flightData[0].Segments[1].FlightNumber
confirm.booking.flightData[0].Segments[2].FlightNumber
I have done both ng-repeat with angular, and without angular I would end up resorting to javascript that loops over data and creates the html dynamically, but I wish to do this the ANGULAR way.. HOW?
HTML with Angular/Javascript Arrays:
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<span style="font-weight: bold;">Flight</span>
</div>
<div class="col-md-4">
<span style="font-weight: bold;">Departs</span>
</div>
<div class="col-md-4">
<span style="font-weight: bold;">Arrives</span>
</div>
</div>
<div class="row">
<div class="col-md-4">
{{confirm.booking.flightData[0].Segments[0].FlightNumber}}
</div>
<div class="col-md-4">
({{confirm.booking.flightData[0].Segments[0].DepartureAirport}})
</div>
<div class="col-md-4">
({{confirm.booking.flightData[0].Segments[0].ArrivalAirport}})
</div>
</div>
</div>
Nesting can be done in repeats, but repeating too much in ng-repeats can be costly in terms of performance as angular creates scopes for each element repeated. Hence, filtering data till the perfect abstracted values that you need in terms of html should be done in the js file.
For eg: if u need only segements in the html form do this, or if u need even flight data in html form follow #Rachel's post
<ul data-ng-repeat="item in confirm.booking.flightData[0].Segments">
<li>{{ item.FlightNumber}}</li>
</ul>
Let's say your data is in flightdetails, then you can go about it like this:
<div ng-repeat="a in flightdetails ">
<div ng-repeat="b in a.booking">
<div ng-repeat="c in b.flightdata">
<div ng-repeat="d in c.segments">
{{d.flightnumber}}
</div>
</div>
</div>
</div>
You can use nested ng-repeat to bind your data - see a demo below:
angular.module("app", []).controller("ctrl", function($scope) {
$scope.confirm = {
booking: {
flightData: [{
Segments: [{
FlightNumber: 1
}, {
FlightNumber: 2
}]
}, {
Segments: [{
FlightNumber: 3
}, {
FlightNumber: 4
}]
}]
}
}
// console.log($scope.confirm);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="wrapper" ng-app="app" ng-controller="ctrl">
<div ng-repeat="x in confirm.booking.flightData">
Data {{$index + 1}}:
<div ng-repeat="y in x.Segments">
<div>Flight No: {{y.FlightNumber}}</div>
</div>
<br/>
</div>
</div>
If you want to display only the following:
confirm.booking.flightData[0].Segments[0].FlightNumber
confirm.booking.flightData[0].Segments[1].FlightNumber
confirm.booking.flightData[0].Segments[2].FlightNumber
then you can use limitTo - see demo below:
angular.module("app", []).controller("ctrl", function($scope) {
$scope.confirm = {
booking: {
flightData: [{
Segments: [{
FlightNumber: 1
}, {
FlightNumber: 2
}]
}, {
Segments: [{
FlightNumber: 3
}, {
FlightNumber: 4
}]
}]
}
}
// console.log($scope.confirm);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="wrapper" ng-app="app" ng-controller="ctrl">
<div ng-repeat="x in confirm.booking.flightData | limitTo : 1">
Data {{$index + 1}}:
<div ng-repeat="y in x.Segments">
<div>Flight No: {{y.FlightNumber}}</div>
</div>
<br/>
</div>
</div>
I created an example here:
http://codepen.io/ackzell/pen/ENBymo
It ultimately looks like this, but check the pen as it has some more info:
<ul>
<li ng-repeat="flight in vm.flightData">
<ul>
<li ng-repeat="segment in flight.Segments">
<em>FlightNumber</em> {{ segment.FlightNumber }}
<br />
<em>Departure:</em> {{ segment.DepartureAirport }}
<br />
<em>Arrival:</em> {{ segment.ArrivalAirport }}
</li>
</ul>
</li>
</ul>
Nesting ng-repeats would help, but maybe you want to give your data some treatment first.

Angular ng-click function populates table?

So I have these boxes that show minimal info for an array created using an ng-repeat. There could be 1 and 10 items returned with objects and their properties These boxes are clickable and when clicked, should populate the table. Problem is, I keep getting a reference error and for the likes of me, cannot see why. The function is defined and should call and fill the table based on the Id of the box to fill the table with more info. The array object is called "swipe".
My html for the the boxes:
<div class="swipeBoxes" ng-repeat="swipe in swipes">
<a href="" ng-click="editSwipe(swipe.id)" >
<div class="swipeBox col-md-12">
<div class="col-md-12 claimObject">
<span class="claimLine" style="width: 3px; position: absolute; top: 5px; left: 5px;">{{ $index + 1 }}.</span>
<span class="claimedLeft">swipe date:</span>
<span class="claimedRight">{{ swipe.date | date: 'MM/dd/yyyy'}}</span>
</div>
<div class="col-md-12 claimObject">
<span class="claimedLeft">provider:</span
><span class="claimedRight">{{ swipe.merchant }}</span>
</div>
<div class="col-md-12 claimObject">
<span class="claimedLeft">amount:</span>
<span class="claimedRight">{{ swipe.amount | currency }}</span>
</div>
</div>
</a>
</div>
My target table that should be filled with data once one of the objects are selected from above:
<div class="swipeDetails col-md-12">
<div class="swipeFlexHead col-md-12">
<p>Swipe Details</p>
</div>
<div class="swipeFlexHead2 col-md-12">
<p>{{ swipe.merchant }}</p>
</div>
<div class="col-md-12">
<div class="swipeFlexElement col-md-4">
<p>Swipe Date</p>
<p>{{ swipe.date | date: 'MM/dd/yyyy' }}</p>
</div>
<div class="swipeFlexElement col-md-4">
<p>Status</p>
<p>{{ swipe.status }}</p>
</div>
<div class="swipeFlexElement col-md-4">
<p>Card Used</p>
<p>{{ swipe.cardHolder }} {{ swipe.cardUsed }}</p>
</div>
</div>
<div class="col-md-12">
<div class="swipeFlexElement col-md-4">
<p>Swipe Amount</p>
<p>{{ swipe.amount | currency }}</p>
</div>
<div class="swipeFlexElement col-md-4">
<p>Amount Requiring Documentation</p>
<p>{{ swipe.reqAmount | currency }}</p>
</div>
<div class="swipeFlexElement col-md-4">
<p>Documentation Due Date</p>
<p>{{ swipe.dueDate | date: 'MM/dd/yyyy' }}</p>
</div>
</div>
</div>
And finally, my controller for this that is pulling data and has the 'editSwipe' function:
app.controller('swipeController', ['$scope', 'swipesService', '$location', 'Upload', '$timeout', '$filter', 'utilsService',
function ($scope, swipesService, $location, Upload, $timeout, $filter, utilsService) {
$scope.swipes = [];
$scope.swipeFormSubmitted = false;
swipesService.getSwipes().then(function (results) {
$scope.swipes = results.data;
});
$scope.swipe = {
id: '',
descr: '',
merchant: '',
date: '',
amount: '',
reqAmount: '',
status: '',
cardUsed: '',
cardHolder: '',
dueDate: ''
}
$scope.editSwipe = function(id) {
$scope.swipeInfo = angular.copy(swipe);
};
}]);
In your editSwipe function you are not doing anything with id. With angular.copy(swipe) you are using swipe which is not defined. I guess you want to copy the swipe you've clicked, then you need to do
ng-click="editSwipe(swipe)"
$scope.editSwipe = function(swipe) {
$scope.swipe = angular.copy(swipe); // I don't see where you use swipeInfo?
};
BTW: is there any need to deep copy the swipe? Can't you just pass the reference $scope.swipe = swipe;

Apply CSS to a unique li inside ng-repeat

I want to change CSS properties for a specific li inside ng-repeat, the loop:
<li id="cmmnt{{$index}}" ng-repeat="comment in ad.comments | orderBy : sortComment : true">
<div class="commentTextArea">
<p id="commentText">{{comment.text | limitTo: 100 }}</p>
<a ng-click="changeEm('cmmnt'+$index)" ng-show="comment.text.length>=10"> {{moreLessText}}
<i class="fa fa-angle-down" style="color: #ee4a4a;"></i>
</a>
</div>
</li>
</ul>
the ng-click="changeEm('cmmnt'+$index)" need to change the height(style.maxHeight) of the liby ID.
here is the function:
$scope.changeEm = function(liElement){ document.getElementById("'liElement'").style.maxHeight ="1em;!important";}
In the console.log() for 'liElement' is just a string and I cant find it by document.getElementById("'liElement'")
Thanks.
You are using a string as variable instead of the variable you pass into the function. I wouldn't recommend this approach, but you can fix it by changing this:
document.getElementById("'liElement'")
to this:
document.getElementById(liElement)
The approach I would recommend is to use ng-class instead:
<li id="cmmnt{{$index}}"
ng-class="{ 'active': comment.clicked }"
ng-repeat="comment in ad.comments | orderBy : sortComment : true">
<div class="commentTextArea">
<p class="commentText">{{comment.text | limitTo: 100 }}</p>
<a ng-click="changeEm(comment)" ng-show="comment.text.length>=10"> {{moreLessText}}
<i class="fa fa-angle-down" style="color: #ee4a4a;"></i>
</a>
</div>
</li>
and in your changeEm function:
$scope.changeEm = function(comment) {
comment.clicked = true;
}
Then you can use the 'active' class in your css:
/* the 'p' in non-clicked 'li' */
li p.commentText {
max-height: 10px;
}
/* the 'p' in a clicked 'li' */
li.active p.commentText {
max-height: auto;
}
The answer was very simple, I just add ng-class:
<div class="commentTextArea">
<p id="commentText" ng-class="comment.active==true?'visable':'notVisable'">{{comment.text}}</p>
</div>
and the function :
$scope.changeEm = function(comment){
console.log(comment);
comment.active = true;
}
finally the match CSS:
.visable {
height: 6.5em !important;
overflow: visible!important;
}
.notVisable{
overflow: hidden!important;
}
Hopes that helps someone!

AngularJS, problems with $index variable in ng-repeat

I'm trying to fill out a 2 column table in AngularJS. I'm using ng-repeat directive to fill out the table, but it's not's working the way I'm planning. My $scope.items is: [Coors, Jameson, Bacardi, Corona]
I want the table to look like this:
| Coors (0) | Jameson (1) |
| Bacardi (2) | Corona (3) |
however, it looks like this:
| Coors (0) | Coors (1) |
| Bacardi (2) | Bacardi (3) |
I'm confused as to why the [$index+1] directive in the my script is only working in the actual text portion of the script (in parenthesis), while the <item-card> div does not seem to properly displaying items[$index+1], and instead is displaying items[$index]. Here is my script:
<div class=row ng-repeat="item in items" ng-if="$index %2 ==0">
<div class="col col-50" ng-if="$index < items.length">
<item-card item="{{item[$index]}}"></item-card>
({{$index}})
</div>
<div class="col col-50" ng-if="$index +1 < items.length">
<item-card item="{{items[$index+1]}}"></item-card>
({{$index+1}})
</div>
</div>
Does anyone know why this might not be working as intended?
Edit: Including is itemcard.html.
<div class = "card" >
<img id = "cardImage" ng-src= "data:image/jpeg;base64,{{item.image}}" width = "100%"/>
{{item.cartQuantity}}
<cardHeader>{{item.itemName}}</cardHeader><br>
<cardHeader ng-if= "item.paksize >1">{{item.paksize}} pack</cardHeader>
<button class="button" ng-click="addToCart(item)">+</button>
<button class="button" ng-click="decrementCart(item)">-</button>
</div>
What you're trying to do seems a little odd to me. Rather than trying to split the array of items into even chunks of 2 columns with Directive Fu, might you consider using lodash.chunk?
<script>
angular.module('example', [ ])
.run(function($scope){
$scope.items = _.chunk([ /* . . . */ ], 2);
});
</script>
<div ng-app="example">
<div class=row ng-repeat="chunk in items">
<div class="col col-50">
<item-card item="{{chunk[0]}}"></item-card>
({{$index}})
</div>
<div class="col col-50">
<item-card item="{{chunk[1]}}"></item-card>
({{$index+1}})
</div>
</div>
</div>
If you wanted to be really Angular about it (a pun!), you could register lodash.chunk as a custom Filter instead:
<script>
angular.module('example', [ ])
.run(function($scope){
$scope.items = [ /* . . . */ ];
})
.filter('chunk', function(){
return _.chunk;
});
</script>
<div ng-app="example">
<div class=row ng-repeat="chunk in items | chunk:2">
<div class="col col-50">
<item-card item="{{chunk[0]}}"></item-card>
({{$index}})
</div>
<div class="col col-50">
<item-card item="{{chunk[1]}}"></item-card>
({{$index+1}})
</div>
</div>
</div>

Categories