1

All.

I written this sort of code before and now I cannot figure out what I'm doing wrong.

This snippet of code is running when the menu buttons are clicked.

$scope.show = function($index){
    console.log($index);
  };

The console log is returning 'undefined'.

Can any one help me figure out what I'm doing wrong?

Js bin below: https://jsbin.com/keteji/edit?html,js,console,output

Help is much appreciated.

Thanks, All

2 Answers 2

2

$index is an iterator offset of the repeated element which is exposed on the local scope of each template instance in ng-repeat

As you have dataArray as menu-list, Use ng-repeat to get iterations in the view

Try this:

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

app.controller('AppController',['$scope',function($scope){
  $scope.dataJson = dataArray;
//   console.log($scope);
  
  
  $scope.show = function($index){
    alert($index);
  };
  
  
  $('.nav li').click(function(){
    $('.nav li').removeClass('active');
    $(this).addClass('active');
  });
  
}]);

var dataArray =[
  {
    "id":1,
    "name":"Home",
    "visible":true
  },
  {
    "id":2,
    "name":"Profile",
    "visible":false
  },
  {
    "id":3,
    "name":"Messages",
    "visible":false
  }
];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="angularApp">
  <div ng-controller="AppController">
    
    <ul class="nav nav-pills">
      <li role="presentation" ng-repeat="d in dataJson" ng-click="show($index)"><a href>{{d.name}}</a></li>
      
    </ul>

    <div class="row">
      
      <div class="col-md-12" ng-repeat="pages in dataJson">
        <h3 ng-show="pages.visible">
          {{pages.name}}
        </h3>
      </div>  
      
      
    </div>
  
  </div>
  
  
</body>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, so much you nailed it with the example.
Happy to help, and welcome to Stackoverflow. If this answer or any other one solved your issue, please mark it as accepted.
2

$index is a property of ngRepeat Scope.

You can't find it on controllers scope.

1 Comment

Thank you very much for the clarification. Still getting the hang of Angular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.