Reputation: 461
I am trying to get the JSON values by using service on angularjs, am trying to print out that as a list.
But, as I expected, it is not working. The error I am getting even from agualr js as well. This below piece of code is not working completely, So that I can't give you what is error that i am getting
Could anyone give me an idea what is wrong here?
html
<!doctype html>
<html ng-app="appNew">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
<script src="controllers1.js"></script>
</head>
<body>
<div ng-controller="contactController">
<H1>Here</H1>
<ul ng-repeat="post in contact">
<li>{{post.title}}</li>
</ul>
</div>
</body>
</html>
js
var app=angular.module('appNew', []);
app.controller('contactController', function($scope, contactServices) {
$scope.contact=contactServices.posts;
console.log($scope.contact);
});
app.service("contactServices", function($scope, $http) {
$http.get('input.json').success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
input JSON
[
{
"id": 1,
"title": "Lorem ipsum 1"
},
{
"id": 2,
"title": "Lorem ipsum 2"
}
]
Error that i am getting
Any help where i went wrong?
Upvotes: 0
Views: 94
Reputation: 15393
Your service scope cannot use in the controllers so use like below code using return
var app=angular.module('appNew', []);
app.controller('contactController', function($scope, contactServices) {
contactServices.getdata('input.json').then(function(success) {
$scope.contact = success.data;
}, function(error) {
});
console.log($scope.contact);
});
app.service("contactServices", function($http) {
var apiClient = {
getdata : getdata
};
return apiClient;
function getdata(uri) {
return $http.get(uri);
}
});
Upvotes: 1
Reputation: 3315
You can use some promise and the promise manager $q.defer().
By definition, $http return promise.
$q.defer() get 2 methods :
resolve(value) : which resolve our associated promise, by giving her the final value
reject(reason) : which resolve an promise error.
Service
(function(){
function Service($http, $q){
//create a defer with $q
var defer = $q.defer();
//Create our promise
var promise = defer.promise;
this.get = function(){
$http.get('input.json').then(function(response){
//Resolve the data
defer.resolve(response.data);
});
return promise;
}
}
angular
.module('app')
.service('Service', Service);
})();
Controller
(function(){
function Controller($scope, Service) {
//Service.get() return a promise
Service.get().then(function(data){
//data is the data from our request
$scope.contact = data;
});
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
Upvotes: 0