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

}]);

問題は、タウン コントローラーでこれら 2 つのコンソール ログを確認できることです。それらはすべて「未定義」を返しました。から値を反復したり取得したりできないようにしますTown.all()。しかし、HomeController では完璧に動作します。

私はサービスと工場の両方を試しました。私は間違った方法でそれをしていると思いますか?ご協力いただきありがとうございます!

4

2 に答える 2

1

Town.all()プロミスを返します。promise は、将来のある時点で返される値のようなものです。それは直接的な価値ではありません。値を取得するために使用できるオブジェクトです。

だから代わりに

$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 に答える