1
\$\begingroup\$

Simple task, I am just trying to have the data that correlates to a menu item hidden until it is clicked. However, I feel like this can be optimized. There are 2 ng-repeats, which is a little redundant but I can't think of another way to do it. What do you think?

See JSFiddle:

<script>
    var app = angular.module('app', []);
    app.controller('ctrl', ['$scope',

    function($scope) {
        $scope.boxes = [{
            link: 'link1',
            content: 'content1'
        }, {
            link: 'link2',
            content: 'content2'
        }];

        $scope.current = {
            item: $scope.boxes[0]
        };
    }]);
</script>
<div ng-app="app" ng-controller="ctrl">
    <ul>
        <li ng-repeat="x in boxes" ng-click="current.item = x">{{x.link}}</li>
    </ul>
    <div ng-repeat="x in boxes" ng-show="x == current.item">{{x.content}}</div>
</div>
\$\endgroup\$
3
\$\begingroup\$

I have made an alternate with only one repeat, though I don't know if it's any better. I'll leave that to you to decide. http://jsfiddle.net/qAFRA/2/

<script>
    var app = angular.module('app', []);
    app.controller('ctrl', ['$scope',

    function($scope) {
        $scope.boxes = [{
            link: 'link1',
            content: 'content1'
        }, {
            link: 'link2',
            content: 'content2'
        }, {
            link: 'link3',
            content: 'content3'
        }, {
            link: 'link4',
            content: 'content4'
        }, {
            link: 'link5',
            content: 'content5'
        }, {
            link: 'link6',
            content: 'content6'
        }];

        $scope.selected = {
            id : 0
        };
    }]);
</script>
<div ng-app="app" ng-controller="ctrl">
    <ul>
        <li ng-repeat="(id, box) in boxes" ng-click="selected.id = id">{{box.link}}</li>
    </ul>
    <div>{{boxes[selected.id].content}}</div>
</div>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.