Question

I have a json data and I want to do this with angularjs :

<ul>
<li>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
</li>
<li>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
</li>
<li>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
    <span>{{data.name}}</span>
</li>
</ul>

I have look to use ng-repeat but I want to insert a li only each 6 span.

<ul>
<li ng-repeat="data in dataset track by $index">
    <span>{{data.name}}</span>
</li>
</ul>

My json file :

[
{
    "name": "test"
}
    "name": "test"
},
{
    "name": "test"
}
]

My controller, it's only get the json file:

function troupesController($scope, $routeParams, $http) {
 $http.get('js/data/troupes.json').success(function(data) {

     $scope.dataset = data;
});

}

Was it helpful?

Solution

In this situation I think the best approach is to use a directive.

Example:

 <div ng-controller="ctrl">
    <ul>
        <div custom-Directive="" dataset="dataset"></div>          
    </ul>

</div>

controller:

function ctrl($scope){
 $scope.dataset = [{name: "test1"},{name: "test2"},{name: "test3"},{name: "test4"},{name: "test5"},{name: "test6"},{name: "test7"},{name: "test8"},{name: "test9"},{name: "test10"},{name: "test11"},{name: "test12"},{name: "test13"},{name: "test14"},{name: "test15"},{name: "test16"},{name: "test17"}]
}

directive:

     app.directive("customDirective", ["$compile", function ($compile) {    

    return {
        restrict: "A",
        scope:{
            dataset:'='
        },
        link: function (scope, element,attr) {
            var html="<li>";
            angular.forEach(scope.dataset,function(item,index){
                 if(index%6==0 && index!==0){
                html+="</li><li>";
                } 
                html+="<span>"+item.name+"</span><br/>";                    
            });
            html+="</li>";
            element.append($compile(html)(scope));
        }
    };
}]);

Live example: http://jsfiddle.net/choroshin/PE5q7/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top