Albert Kuzmin Albert Kuzmin - 1 month ago 11
Ajax Question

AngularJS load ng-repeat into another ng-repeat with ajax call

I'm new to angular and would like some help in solving the following issue. This is the code I currently have, simply getting an array of results from the server using a post request and displaying them using the ng-repeat directive:

<div id="mainW" ng-controller="MediaController">

<div id="mediaBodyW" ng-repeat="media in medias">
<div class="mediaW" data-id="{{media.id}}">
<div class="mediaNum">{{media.num}}</div>
<div class="mediaN">{{media.name}}</div>

<div id="loadSubs" ng-click="loadSubMedias(media.id)">load sub medias</div>
<div id="subMediaW"></div>

</div>
</div>


This is my controller:

app.controller("MediaController",['$scope','$http','$httpParamSerializerJQLike',function($scope,$http,$httpParamSerializerJQLike){

$scope.medias = [];

try {
$http({
method: 'POST',
url: 'media.php',
data: $httpParamSerializerJQLike({"request":"getAllMedia"}),
headers: {'Content-Type':'application/x-www-form-urlencoded'}
}).then(function (ans) {
$scope.medias = ans.data;
}, function (error) {
console.error(JSON.stringify(error));
});
}
catch (ex) {
console.error("Error: " + ex.toString());
}
}]);


Now, what I would like to achieve, is: on clicking the div with id of "loadSubs", run another $http post query which will load an array of results into the "subMediaW". Of course the query and appending of html should be unique for each media element, and each time a data is loaded for a particular element all previous results should be cleared, all this while taking into account that the loaded data will be also manipulated in the future.

Can someone please help me understand how can I do this using AngularJS?

Answer

Firstly you should have a function in your controller with the name loadSubMedias and instead of simply taking media.id you can send whole media object to it (later on we will add new data into this object as an another property).

$scope.loadSubMedias = function (media) {
    $http({
        method: 'POST',
        url: 'media.php',
        data: $httpParamSerializerJQLike({"mediaId":media.id}),
        headers: {'Content-Type':'application/x-www-form-urlencoded'}
    }).then(function (response) {
        // now add subDatas into main data Object
        media.subMedias = response.data;
    });
}

and in your controller just use ng-repeat like this

<div id="mainW" ng-controller="MediaController">

    <div id="mediaBodyW" ng-repeat="media in medias">
        <div class="mediaW" data-id="{{media.id}}">
        <div class="mediaNum">{{media.num}}</div>
        <div class="mediaN">{{media.name}}</div>

        <div id="loadSubs" ng-click="loadSubMedias(media)">load sub medias</div>
        <div id="subMediaW" ng-repeat="subMedia in media.subMedias">
             <pre>{{subMedia | json}}</pre>
        </div>

    </div>
</div>
Comments