0

伙计们,我是 Angularjs 的新手,这是我的新单页应用程序的一些代码。但我认为我做得不对。这是我的上帝:

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 : '/'
  });

}]);

所以,问题是您可以在 Town 控制器中看到这两个控制台日志,它们都返回“未定义”。这样我就无法迭代或从中获取值Town.all()。但它在 HomeController 上运行完美。

我对服务和工厂都很熟悉。我认为我只是以错误的方式做事?谢谢你的帮助!

4

2 回答 2

1

您的错误是您尝试以同步方式从服务器检索数据,这在 Angular 中不起作用(通常在 javascript 中也不起作用)。

将服务代码更改为:

TownApp.service('Town', function($http) {
    this.all = function() {
        return $http.get('/database.json');
    };
});

然后将控制器代码更改为:

 TownApp.controller('HomeCtrl',function($scope,Town){
    Town.all().then(function(response)) {
      $scope.towns = response.data;
      console.log($scope.towns.length);
    }
}
于 2013-08-21T14:00:10.130 回答
1

Town.all()返回一个承诺。承诺就像是在未来某个时间返回的值。这不是直接的价值。它是一个可用于检索值的对象。

所以而不是

$scope.towns = Town.all();

你需要:

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;    
    });
于 2013-08-21T14:01:51.233 回答