Reputation: 1456
I have two objects, programme and section, each programme has some sections I have two services, the first service shows all programmes, and the second service shows all sections for one programme, the problem is : I can't show each sections for one programme using the code of programme as a parameter, this is my code :
var app=angular.module("myApp",[]);
app.controller("myController",function($scope,$http){
$scope.programme=null;
$scope.section=null;
$http.get("/programmes").success(function(response) {
$scope.programme = response;
});
//getting sections for one programme using code
$scope.getSectionByCode = function(code)
{
$http.get("/listsections/"+code).success(function(data){
$scope.section = data;
});
};
});
HTML
<div class="padd" ng-app="myApp"
ng-controller="myController">
<ul>
<li ng-repeat="x in programme"
ng-init="getSectionByProgCode(x.code)" >
{{x.titre}}
<ul>
<li ng-repeat="s in section">{{s.title }}</li>
</ul>
</li>
</ul>
</div>
the result of this code is :
programme 1
Section title 4
Section title 5
programme 2
Section title 4
Section title 5
but im looking for this result :
programme 1
Section title 1
Section title 2
Section title 3
programme 2
Section title 4
Section title 5
Note : when I check my browser log, I find that the service of section get the results properly for each programme.
Upvotes: 3
Views: 861
Reputation: 17064
First of all I would advise you to read about how to structure your app properly, e.g. place http calls in services, store data in services, etc.
Now - your problem is that you do 2 asynchronous calls and place both results on the same variable: $scope.section
, so obviously both ng-repeat
divs will show the same data.
One way to fix that is you could make the $scope.section
variable an array and store by index:
ng-init="getSectionByProgCode(x.code, $index)"
And in your controller:
$scope.section = [];
$scope.getSectionByCode = function(code, index)
{
$http.get("/listsections/"+code).success(function(data){
$scope.section[index] = data;
});
};
HTML function name and controller function name don't match, I'm guessing it's a typo of yours.
A different way to solve it (preferable by me and fellow commentators), is to store your section data under the programme itself:
<li ng-repeat="x in programme"
ng-init="getSectionByProgCode(x)" >
{{x.titre}}
<ul>
<li ng-repeat="s in x.section">{{s.title}}</li>
</ul>
</li>
And in your controller:
$scope.getSectionByProgCode = function(programme)
{
$http.get("/listsections/" + programme.code).success(function(data){
programme.section = data;
});
};
Upvotes: 5