如何使用angularJS restful服务从外部文件中使用json数据

时间:2012-12-13 11:37:17

标签: angularjs

我正在开发一个应用程序。我正在从

中检索json数据

使用$ http.get()方法的外部文件,它工作正常。现在我正在尝试使用角度

宁静的服务。它在过滤器中运行良好,但是当我在控制器中使用它时

显示未定义。

//Service.js File
angular.module('calenderServices', ['ngResource']).
factory('Events', function($resource){
return $resource('/EventCalender/:File.json', {}, {
query: {method:'GET', params:{File:'events'}, isArray:true}
});
});


        //This is my app Module
angular.module('calender', ['eventFilters','highlight','event','calenderServices']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
  when('', {templateUrl: 'template.html',   controller: MonthCtrl}).
  otherwise({redirectTo: '/invalid'});
}]);


     //This is my filter.js
angular.module('eventFilters', ['calenderServices']).filter('compare', function(Events) {
var events=Events.query();
alert(events[0].name); //it is displaying the name "Milestone1" });


     //This is my controller.
function MonthCtrl($scope, Events){
var events=Events.query();
    alert(events[0].name); //it is displaying undefined
    }

     //whenever i try to use the variable 'events' in controller, it is displaying undefined or null.  But in filter it is working fine. 

1 个答案:

答案 0 :(得分:2)

以下内容无效,因为 ngResource 会生成 异步 http请求。

var events=Events.query();
alert(events[0].name); // <--- here events is an empty array

通常您需要做的就是以下内容,您的数据可以在视图中呈现

$scope.events = Events.query()

它看起来像是一个同步操作,但事实并非如此。这是角度的禅在工作。您可以了解details from the docs

要进一步处理数据,您还可以将成功回调传递给get方法

Events.query(function(events){
    // here you have access to the first event's name
    console.log(events[0].name);
});

这是一个有效的例子:http://plnkr.co/edit/NDZ2JWjMUoUvtzEuRUho?p=preview