Reputation: 11
I have a service that is used to share data between 2 controllers and retrieves a data list:
myApp.service('DataService', function($http) {
this.data = [];
this.loadData = function() {
$http.get('/api/data').success(function(data) {
this.data= data;
})
};
});
which is called in my controller:
myApp.controller('appController', function($scope, DataService) {
$scope.DataService= DataService;
DataService.loadData();
});
and displayed here:
<div ng-controller="appController">
<li ng-repeat='item in DataService.data'>
<a href="#item/{{item.ID}}"> View Item</a>
</li>
</div>
When this is ran, it doesn't display anything. I have ran it with some alert boxes and can see that the data list is populated with the data I want to display but no information is displayed otherwise.
Upvotes: 1
Views: 87
Reputation: 981
Not sure if I've got this right but...by calling the method on the service itself instead of on the service assigned to the $scope won't that make it Angular JS miss the watch on the data property completely?
Upvotes: 0
Reputation: 245419
You're using your service incorrectly. Right now, it's going to be hard for Angular to watch the property on your service for changes. Instead of storing the data as a property on itself, it should simply return it to the caller. Try:
myApp.service('dataService', function($http) {
this.loadData = function() {
return $http.get('/api/data').then(function(data) { return data; });
}
}
Which is then called in the controller like:
myApp.controller('appController', function($scope, dataService) {
$scope.data = dataService.loadData();
});
And bound to in the view like:
<div ng-controller="appController">
<li ng-repeat="item in data track by $id">
<a href="#item/{{ item.ID }}">View Item</a>
</li>
</div>
Upvotes: 4
Reputation: 104775
Have to return a promise and use .then
to access it:
this.loadData = function() {
return $http.get('/api/data').then(function(data) {
return data.result
})
};
Ctrl:
DataService.loadData().then(function(data) {
$scope.DataService = data;
});
Upvotes: 1