【问题标题】:How do i use json data from external file using angularJS restful service如何使用 angularJS restful 服务使用来自外部文件的 json 数据
【发布时间】:2012-12-01 07:01:38
【问题描述】:

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

中检索 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. 

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    由于 ngResource 发出 异步 http 请求,因此以下操作无效。

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

    通常您只需执行以下操作,您的数据就可以在您的视图中呈现

    $scope.events = Events.query()
    

    它看起来像一个同步操作,但事实并非如此。这是 Angular 的禅意。你可以学习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

    【讨论】:

    • 我试过这个,它不起作用。我刚刚将名称“$scope.events”更改为“$scope.eve”,它现在正在工作。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 2013-06-09
    • 1970-01-01
    相关资源
    最近更新 更多