访问每个ng-repeat项目的范围

时间:2017-01-22 09:49:56

标签: javascript angularjs

我对angularjs有些新意。我使用ng-repeat列出我页面中的实体,每个实体对象都有一个href属性到它的字段。我想当有人点击链接,检索字段并在父实体下面的另一个嵌套ul上显示它们。 这是我的HTML:

<ul>
    <li class="" ng-repeat="entity in entities" >
        {{entity.name}}
        <a class="entity-fields" ng-click="retrieveFields(entity.fields.href)" >fields</a>
        <ul class="fields" >
            <li class="fields" ng-repeat="field in fields" > {{field.name}} </li>
        </ul>
    </li>
</ul>

这是我的javascript:

myApp.controller('excelController', ['$scope', '$http', function($scope, $http) {
    $scope.baseUri = "http://localhost:8080/rst/api/v1/introspection";
    $scope.entitiesUri = $scope.baseUri + "/entities";

    $scope.retrieveFields = function(href){
        $http.get(href).then(function success(response){
            $scope.fields = response.data;
        });
    };

    $http.get($scope.entitiesUri).then(function success(response){
        $scope.entities = response.data;
    });
}]);

但是当我点击链接并检索实体的字段时,它会在所有实体下方显示它们。 如何使其仅显示每个项目范围内的字段。

提前致谢

1 个答案:

答案 0 :(得分:1)

您必须更改代码的某些部分

<ul>
<li class="" ng-repeat="entity in entities track by $index" >
    {{entity.name}}
    <a class="entity-fields" ng-click="retrieveFields($index,entity.fields.href)" >fields</a>
    <ul class="fields" >
        <li class="fields" ng-repeat="field in entity.fieldItems" > {{field.name}} </li>
    </ul>
</li>

那么您需要将检索功能更改为:

$scope.retrieveFields = function(index,href){
    $http.get(href).then(function success(response){
        $scope.entities[index].fieldItems = response.data;
    });
};

这可以解决您的问题。