I am newer to angular/js. I'm using ng-repeat to repeat results (as list-items) from a webservice. I have to use some of the fields from the json results to create a dynamic URL to use on my webpage for each ng-repeat item. Everything repeats back fine except for my custom URL.
Side note, I am also doing pagination - with 5 list-items per page. This is working correctly.
controller snippet:
$scope.stores = response.data;
$scope.jsonSize = $scope.stores.length;
for (var i = 0; i<=$scope.jsonSize - 1; i++) {
$scope.storeSize = $scope.stores[i].SIZE;
$scope.empCount = $scope.stores[i].EMPLOYEE_COUNT;
$scope.customUrl = 'http://test.com/' + $scope.storeSize + ',' + $scope.empCount;
console.log("custom url is " + $scope.customUrl);
}
webservice/json snippet:
[{"STORE_ID":"001","SIZE":1000,"EMPLOYEE_COUNT":45},
{"STORE_ID":"002","SIZE":500,"EMPLOYEE_COUNT":25},
{"STORE_ID":"003","SIZE":750,"EMPLOYEE_COUNT":40}]
jade snippet:
li(ng-repeat="store in stores | startFrom:currentPage*pageSize | limitTo:pageSize" )
.store-link
a(ng-href="{{customUrl}}" target="_blank") Employees
My console.log returns the correct URL for each result. The webpage creates the Employees link, however, the href value for every result item ends up being http://test.com/750,40 - from the last result.
I have tried ng-click and putting the URL into a function. I have tried href and ng-href as well, without any luck. Am I not binding this correctly or could my loop be messing things up?
Any help would be much appreciated!
Probably because your for
loop is overwriting $scope.customUrl
with each loop. Make it a collection, append to it, and then use that:
$scope.customUrls = [];
for (var i = 0; i<=$scope.jsonSize - 1; i++) {
$scope.storeSize = $scope.stores[i].SIZE;
$scope.empCount = $scope.stores[i].EMPLOYEE_COUNT;
var url = 'http://test.com/' + $scope.storeSize + ',' + $scope.empCount;
$scope.customUrls.push(url);
console.log("custom url is " + $scope.customUrls[i]);
}
And the view:
li(ng-repeat="store in stores | startFrom:currentPage*pageSize | limitTo:pageSize" )
.store-link
a(ng-href="{{customUrls[$index]}}" target="_blank") Employees
What's probably better is to just add a property to your stores collection with the URL:
for (var i = 0; i<=$scope.jsonSize - 1; i++) {
$scope.storeSize = $scope.stores[i].SIZE;
$scope.empCount = $scope.stores[i].EMPLOYEE_COUNT;
var url = 'http://test.com/' + $scope.storeSize + ',' + $scope.empCount;
$scope.stores[i].url = url;
console.log("custom url is " + $scope.stores[i].url);
}
li(ng-repeat="store in stores | startFrom:currentPage*pageSize | limitTo:pageSize" )
.store-link
a(ng-href="{{store.url}}" target="_blank") Employees