\$\begingroup\$
\$\endgroup\$
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-repeat
s, 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>
Josue EspinosaJosue Espinosa
asked Jul 11, 2014 at 21:55
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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>
answered Jul 11, 2014 at 22:31
default