使用ng-init和ng-repeat时会出现问题

时间:2015-06-04 18:13:42

标签: javascript angularjs

我使用以下loadLocation(asset.id)函数来加载特定资产的位置,使用ng-repeat和ng-init,但我得到所有行的最新location.city和location.state

   <tr ng-repeat="asset in assets">
        <td>{{asset.name}}</td>
        <td>{{asset.obj_type.name}}</td>
        <td ng-init="loadLocation(asset.id)">
             {{location.city}}
        </td>
        <td>{{location.state}}</td>
   </tr>

角度控制器

    $scope.loadLocation= function(assetId) {
     Location.locationByIsprimary({assetId: assetId}, function(result) {
                $scope.location=result;
            });
        };

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

您只在location内创建scope一次,您需要为ng-repeat数组中的每个元素创建它,以便反映在html上。

<强>标记

<tr ng-repeat="asset in assets">
    <td>{{asset.name}}</td>
    <td>{{asset.obj_type.name}}</td>
    <td ng-init="loadLocation(asset)">
         {{asset.location.city}}
    </td>
    <td>{{asset.location.state}}</td>
</tr>

<强>代码

$scope.loadLocation= function(asset) {
 Location.locationByIsprimary({assetId: asset.id}, function(result) {
            asset.location=result;
        });
    };