Jesse McIntosh Jesse McIntosh - 1 year ago 110
AngularJS Question

How to DRY up list in angular

This is my first time posting a question on stackoverflow so sorry if its not in the correct format.

I keep running into the same problem in angular and i'm sure there is a very simple way to solve it but for some reason i can't figure it out. I will post an example and give an explanation below.

<div class="jmc-navbar-content" ng-if="!vm.isHidden" ng-swipe-up="vm.toggleNav()">
<!-- contains the navigation/page links -->
<ul class="jmc-navbar-menu">
<li class="active"><a class="noPreventDefault" ng-click="vm.toggleNav()" ng-href="#home">Home</a></li>
<li><a class="noPreventDefault" ng-click="vm.toggleNav()" ng-href="#portfolio">Portfolio</a></li>
<li><a class="noPreventDefault" ng-click="vm.toggleNav()" ng-href="#about">About</a></li>
<li><a class="noPreventDefault" ng-click="vm.toggleNav()" ng-href="#contact">Contact</a></li>
<li><a class="noPreventDefault" ng-click="vm.toggleNav()" ng-href="#/">View source on GitHub</a></li>

Although this works i don't like having to repeat myself for all the
tags which need to have the same classes and attributes. I can think of multiple ways in which to do this with javascript but they all seem a little 'hack-y'. Is there any simple way to do this in Angular or Javascript?

Thanks for taking the time to reply, any and all constructive criticism is appreciated.

Answer Source

In your html use ng-repeat

And as your first li has the class as 'active', you need to use $index

<div ng-repeat = 'aVal in aVals'>
     <li ng:class="{true:'active', false:''}[$index == 0]"><a class="noPreventDefault" ng-click="vm.toggleNav()" ng-href="aVal.hrefVal">{{}}</a></li>

And in angularController

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

.controller('myCtrl', ['$scope',
    function ($scope) {
         $scope.aVals= [
            { hrefVal: '#home', name='Home'},
            { hrefVal: '#portfolio', name='Protfolio'},
             // so on

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download