[英]Creating dynamic inside ngrepeat - every href value is the same
我是angular / js的新手。 我正在使用ng-repeat從Web服務重復結果(作為列表項)。 我必須使用json結果中的某些字段來創建動態URL,以便在我的網頁上為每個ng-repeat項目使用。 除了我的自定義網址外,其他所有內容都可以重復播放。
旁注,我也在做分頁-每頁5個列表項。 這工作正常。
控制器代碼段:
$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片段:
[{"STORE_ID":"001","SIZE":1000,"EMPLOYEE_COUNT":45},
{"STORE_ID":"002","SIZE":500,"EMPLOYEE_COUNT":25},
{"STORE_ID":"003","SIZE":750,"EMPLOYEE_COUNT":40}]
玉片:
li(ng-repeat="store in stores | startFrom:currentPage*pageSize | limitTo:pageSize" )
.store-link
a(ng-href="{{customUrl}}" target="_blank") Employees
我的console.log為每個結果返回正確的URL。 該網頁創建了Employees鏈接,但是,每個結果項的href值最終都是http://test.com/750,40-從最后一個結果開始。
我嘗試了ng-click並將URL放入函數中。 我也嘗試過href和ng-href,沒有任何運氣。 我是不是正確綁定了這個綁定,否則我的循環會把事情弄亂嗎?
任何幫助將非常感激!
可能是因為您的for
循環在每個循環中都覆蓋了$scope.customUrl
。 使其成為一個集合,追加到它之后,然后使用它:
$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]);
}
和視圖:
li(ng-repeat="store in stores | startFrom:currentPage*pageSize | limitTo:pageSize" )
.store-link
a(ng-href="{{customUrls[$index]}}" target="_blank") Employees
可能更好的方法是使用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
您應該修改存儲以包含所有邏輯以便於查看。 您顯然可以使用$index
來查找不同的數組,但是就我而言,這並不是真正合乎邏輯的方法。
$scope.stores = response.data.map(function(storeData) { return { storeSize: storeData.SIZE, empCount: storeData.EMPLOYEE_COUNT, url: 'http://test.com/' + storeData.SIZE + ',' + storeData.EMPLOYEE_COUNT; }; });
li(ng-repeat="store in stores | startFrom:currentPage*pageSize | limitTo:pageSize" ) .store-link a(ng-href="{{ store.url }}" target="_blank") Employees
理想情況下,您檢索服務中的數據並將所有原始數據轉換為模型,然后僅使用這些模型來填充視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.