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

JSA*_*ict 6 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. 
Run Code Online (Sandbox Code Playgroud)

jai*_*ime 2

以下内容不起作用,因为ngResource发出异步http 请求。

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

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

$scope.events = Events.query()
Run Code Online (Sandbox Code Playgroud)

它看起来像是同步操作,但事实并非如此。这就是 Angular 的禅宗在起作用。您可以从文档中了解详细信息。

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

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

这是一个工作示例:http://plnkr.co/edit/NDZ2JWjMUoUvtzEuRUho ?p=preview