从Angular Factory调用JSON文件无效

时间:2014-10-06 13:00:10

标签: javascript json angularjs

我是AngularJS的新手。我试图从工厂函数调用json文件,但它显示我的var customers = [];数组没有更新。请帮忙。

以下是我的代码。

var demoApp = angular.module("myApp", []);

demoApp.factory('simpleFactory', ['$http', function($http){

    return {

        getCustomer: function(){
            var customers = [];
            return $http.get("http://www.w3schools.com/website/Customers_JSON.php")
            .success(
                function(data){

                    customers = data;
                },
                function(error){
                    console.log(error);
                });
            console.log(customers)
        }

    }

}]);

demoApp.controller("emplyCtrl", function($scope, simpleFactory){
    $scope.customers = simpleFactory.getCustomer();
});

Demo Fiddle

3 个答案:

答案 0 :(得分:3)

尝试这样的事情:

demoApp.factory('simpleFactory', ['$http', function($http){

    return {

        getCustomer: function(){

            return $http.get("json/customers.json").then(
                function(response){
                    var customers = [];
                    customers = response.data;
                },
                function(error){
                    console.log(error);
                });

        }

    }
}]);

答案 1 :(得分:1)

在你的控制器中使用它:

demoApp.controller("emplyCtrl", function($scope, simpleFactory){
    simpleFactory.getCustomer().then(function(response){
        $scope.customers = response.data;
    });
});

由于视图(HTML)从控制器的$scope读取,因此您必须将数据放在控制器中的某个位置$scope。在工厂中进行设置只允许从工厂内进行访问。

Here is the working Fiddle

希望这有帮助!

答案 2 :(得分:-1)

你认为不应该把" $"在http之前签名? 我认为' $ http'应该表明它是可序列化的。这就是为什么,$ http应该在参数部分中说明,就像你在前面的字符串语句中提到的那样。

此外,您不能只使用http,因为语法是在http前面使用$。 否则,angular dll将无法识别您的代码。

demoApp.factory(' simpleFactory',[' $ http',功能($ http){

var customers = [];

$http.get("json/customers.json")
    .success(function(data){
    customers = data;
});

var factory = {};

factory.getCustomer = function(){
    return customers;
};

return factory;

}]);

看一下这里的例子: http://www.w3schools.com/angular/angular_http.asp

谢谢,