Mehran
Mehran

Reputation: 67

access to scope of each ng-repeat item

I am sort of new to angularjs. I am using ng-repeat to list entities in my page, each entity object has an href property to it's fields. I want when someone clicks on the link, retrieve the fields and show them on another nested ul below the parent entity. here's my 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>

and this is my 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;
    });
}]);

but when I click on the link and retrieve fields of an entity, it shows them below all of the entities. how can I make it to only show the fields in the scope of each item.

Thanks in advance

Upvotes: 1

Views: 534

Answers (1)

Hamid
Hamid

Reputation: 121

You have to change some part of your code

<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>

then You need to change your retrieve function as:

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

This should fix your problem.

Upvotes: 1

Related Questions