guys I'm new to Angularjs, here's some code of my new single-page app. But I think I'm not doing it right. Here is my gode:
var TownApp=angular.module('TownApp',['ngRoute','ngResource']);
TownApp.service('Town', function($http) {
this.all = function() {
return $http.get('/database.json').then(function(response){
return response.data;
})
};
});
var HomeCtrl = TownApp.controller('HomeCtrl',function($scope,Town){
$scope.towns = Town.all();
});
var TownCtrl = TownApp.controller('TownCtrl',function($scope, $routeParams, Town){
console.log(Town.all().length)
$scope.towns = Town.all();
console.log($scope.towns.length)
//........
})
TownApp.config(['$routeProvider', function($routes) {
$routes.when('/',{
templateUrl : 'welcome.html',
controller : 'HomeCtrl'
}).when('/town/:townId',{
templateUrl : 'town.html',
controller : 'TownCtrl'
}).otherwise({
redirectTo : '/'
});
}]);
So, the question is you can see those two console logs in Town controller, they all returned 'undefined'. So that I can't iterate or get values from Town.all()
. But its working perfect on HomeController.
I've treid with both service and factory. I think I'm just doing it in wrong way? Thanks for your help!
Your mistake is that you try to retrieve the data from the server in a synchronous way, which doesn't work in angular (nor in javascript in general).
Change the service code to:
TownApp.service('Town', function($http) {
this.all = function() {
return $http.get('/database.json');
};
});
And then change the controller code to:
TownApp.controller('HomeCtrl',function($scope,Town){
Town.all().then(function(response)) {
$scope.towns = response.data;
console.log($scope.towns.length);
}
}
Town.all()
returns a promise. A promise is like a value to be returned some time in the future. It's not directly the value. It's an object that can be used to retrieve the value.
So instead of
$scope.towns = Town.all();
you need:
Town.all()
.then(function(response){
//if the promise we are dealing with is the promise that was directly
//returned from the $http call, then we need response.data
//if it was projected to hold `response.data` before (as in the initial question)
//then "response" here is already holding our data.
$scope.towns = response;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.