Question

I am new to angular. I am trying to find a way to render half of a data array into one div and the other one to another div.

angular.module("testApp", []).controller('mainCtrl', function($scope){
  $scope.data = [{name:'a'},{name:'b'},{name:'c'},{name:'d'}];
});

My template looks like this

<div ng-controller="mainCtrl">
  <ul>
    <li ng-repeat="item in data">{{item.name}}</li> // Render only <li>a</li> <li>b</li>
  <ul>

    <div> SOME OTHER CONTENT</div>
   <ul>
    <li ng-repeat="item in data">{{item.name}} // Render only <li>c</li> <li>d</li>
  <ul>
</div>

I would like to use the same controller instead of using 2 different ones to render different content but i cannot make it work.

Any help is greatly appreciated. Thank you, Zaver

Was it helpful?

Solution

It looks like you could use a custom filter to resolve this, for example:

Custom Filter:

var app = angular.module('myApp', []);

app.filter('myFilter', function() {
  return function(items, param1) {
    var end= param1 == 1 ? Math.floor(items.length/2) : items.length ;
    var start =  param1 == 1 ? 0 : Math.floor(items.length/2) ;
    console.log("param ",param1," start: ", start, " end: ", end);
    return items.slice(start, end);
    };
});

Html

<ul>
   <li ng-repeat="item in items|myFilter:1">{{item.name}}</li>
</ul>
<div>second have</div>
<ul>
    <li ng-repeat="item in items|myFilter:2">{{item.name}}</li>
</ul>

Where in your filter |myFilter:1 you set which half you want 1|2.

Note: I thought about using a notation like '50%>' and '<50%' instead of 1|2 looking for a interesting way to make the filter more clear and extensible with possibilities to do things like 25%<, 75%> but I wasn't sure if it was necessary in your scenario. Hopefully 1|2 will do the trick.

Here is plunker demo

OTHER TIPS

You can use the slice method of the array to select the parts you give to the ng-repeat:

<div ng-controller="mainCtrl">
  <ul>
    <li ng-repeat="item in data.slice(0, data.length/2)">
      {{item.name}}  // Render only a and b
    </li>
  <ul>

  <div> SOME OTHER CONTENT</div>
  <ul>
    <li ng-repeat="item in data.slice(data.length/2)">
      {{item.name}} // Render only c and d
    </li>
  <ul>
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top