1

我创建了一个工厂来检索一个 json 文件。我确实看到该对象在调用后在我的控制台中输出,但数据没有显示在我的视图中。我在控制器中没有正确调用工厂吗?

这是我的应用程序:

var tools = angular.module("tools", [])

tools.config(function ($routeProvider) {

    $routeProvider.when('/home', {
        templateUrl: 'home.html',
        controller: 'HomeController'
    });
    $routeProvider.when('/about', {
        templateUrl: 'about.html',
        controller: 'AboutController'
    });




    $routeProvider.otherwise({
        redirectTo: '/home'
    })

});

tools.controller("HomeController", function ($scope, fetchData) {

    $scope.record = fetchData.getData();
    $scope.clearSearch = function () {
        $scope.search = "";
        $scope.name2 = "";
    }
    $scope.name2 = "";
    $scope.search = "";



});


tools.controller("AboutController", function ($scope) {
    //nothing yet
});



tools.factory('fetchData', function ($http) {
    return {
        getData: function () {
            $http({
                method: 'GET',
                url: 'list.json'
            }).
            success(function (data, status, headers, config) {
                console.log(data);
                return data;
            });
        }
    }


});
4

1 回答 1

2

The $http call is asynchronous (as are all AJAX requests), so thereturn statement in your callback isn't actually returning it data to your controller. You'll either want to look into using $resource, which can work almost as you've written it, or pass a callback to getData like:

In your Controller:

fetchData.getData(function (data) {
    $scope.record = data;
});

In your Service:

tools.factory('fetchData', function($http) {
    return {
        getData: function(cb) {
            $http({method: 'GET', url: 'list.json'}).success(cb);
        }
    }
});
于 2013-05-16T19:04:15.780 回答