Reputation: 1030
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
Upvotes: 1
Views: 1608
Reputation: 36609
$index
is an iterator offset of the repeated element which is exposed on the local scope of each template instance inng-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>
Upvotes: 2
Reputation: 25352
$index
is a property of ngRepeat
Scope.
You can't find it on controllers scope.
Upvotes: 2