Kranthi Kranthi - 12 days ago 9
AngularJS Question

ng-init not working if multiple items in angularjs, but working for single item


I am new to stackoverflow, Sorry if this question is not proper.

I had declared a function in ng-init within the ng-repeat(session) to
get the questions length by passing session id.


//This is the HTML Part
<tr ng-repeat="session in sessionslist" ng-init='getQuestionsofSession(accessors.getId(session))' >
<td>{{session.name}}</td>
<td>{{session.speakers.length}}</td>
<td><p>{{questions.length}}</p></td>
</tr>

//This is the ANGULAR Part
$scope.getQuestionsofSession = function(sessionid){
$http.get('/api/audiencepanel/getquestions/'+sessionid)
.success(function(data){
$scope.questions= data;
});
};

//Getting sessions list
$scope.getsessions= function(){
$http.get("api/getsession/"+$stateParams.id).success(function(data){
$scope.sessionslist = data;
});



So if the session length is single, ng-init is working, but sessions
length multiple it is not showing any data. $scope.questions is not
showing any data

By the way, Session table is different and Question table is
different, questions are stored based on session id. So need questions data in session data based on session id

Is there any other way to get this worked?

Answer

Inside each ng repeat we have different scope. So question object in sessionslist[0] is not same as sessionslist[1]

Instead of using init you could do like this

$scope.getsessions= function(){
   $http.get("api/getsession/"+$stateParams.id).success(function(data){
   angular.forEach(data, function(value, key){
      $http.get('/api/audiencepanel/getquestions/'+value.id)
            .success(function(data1){                
                value.questions= data1;
            });
   });
   $scope.sessionslist = data;
});
Comments