Reputation: 10964
I have the following function:
$scope.getObjectCount = function() {
var theLength = _.flatten($scope.myObjects);
var i;
for ( i = 0; i < theLength.length; i++) {
//return i here??
}
return i;
}
theLength.length evaluates to '5' as there are 5 objects in myObjects.
This is called inside an ng-repeat, it's called 5 times. I want it to return 0, 1, 2, 3 and finally 4. But it's returning 5 each time.
What I want to do is return the index of each object in the array, so I'm counting them and returning i each time... or trying to.
Can anyone suggest how I might fix this?
Upvotes: 0
Views: 68
Reputation: 4400
You can create an angular factory that will serve as a counter if this is something you only use in one part of your app. Since the data is encapsulated in the service you can call it from anywhere.
.factory("MyCounter", function() {
var start = 0;
return {
increment: function() {
start += 1;
},
currIndex: function() {
return start;
},
reset: function() {
start = 0;
}
};
});
Now just inject this dependency into a controller and call it in your view.
For example:
.controller("MyController", function(MyCounter) {
// Publish our counter object to scope
$scope.counter = MyCounter;
});
In your view:
<div some-value="counter.increment()">...</div>
Upvotes: 1
Reputation: 2573
If you simply want an increment of one in the value you're returning each time, then this simple function should do good for you:
var i = -1;
function returnCount(){
i++;
return i;
}
alert(returnCount()); // 0
alert(returnCount()); // 1
alert(returnCount()); // 2
alert(returnCount()); // 3
alert(returnCount()); // 4
But i believe this will cause problems in long run.. so if this is not what you were looking for then you should explain it better, because from your response to my comment, all i could get was you want to do this what i wrote above..
EDIT You should use theLength property at the place where you're calling the function:
This will be your ng-repeat part:
for(var i=0; i<theLength; i++){
returnCount();
}
Now this will run till the count of objects and return their indexes 0,1,2,3,4...
Upvotes: 0