处理角度js中来自$ resource的数据响应

时间:2013-11-01 03:08:15

标签: angularjs laravel laravel-4 angularjs-scope angular-resource

我有一个RESTful应用Laravel 4Angular JS

在我的Laravel控制器中,

public function index() {

  $careers = Career::paginate( $limit = 10 );

  return Response::json(array(
    'status'  => 'success',
    'message' => 'Careers successfully loaded!',
    'careers' => $careers->toArray()),
    200
  );
}

和角度剧本,

var app = angular.module('myApp', ['ngResource']);

app.factory('Data', function(){
    return {
        root_path: "<?php echo Request::root(); ?>/"
    };
});

app.factory( 'Career', [ '$resource', 'Data', function( $resource, Data ) {
   return $resource( Data.root_path + 'api/v1/careers/:id', { id: '@id'});
}]);

function CareerCtrl($scope, $http, Data, Career) {

    $scope.init = function () {
        $scope.careers = Career.query(); 
    };
}

这里我很难处理响应数据以分配给范围变量,现在我在[]中得到空数组$scope.careers。以及如何处理成功和错误以显示以下正常$http service

之类的消息
$scope.init = function () {

    Data.showLoading(); // loading progress
    $http({method: 'GET', url: Data.root_path + 'api/v1/careers'}).
    success(function(data, status, headers, config) {
        Data.hideLoading();
        $scope.careers = data.careers.data;
    }).
    error(function(data, status, headers, config) {

        if(data.error.hasOwnProperty('message')) {
            errorNotification(data.error.message); 
        } else {
            errorNotification();
        }

        $scope.careers = [];
    });
};

使用$ resource在控制台中查看我的请求。

enter image description here

2 个答案:

答案 0 :(得分:15)

试试这个:

app.factory( 'Career', [ '$resource', 'Data', function( $resource, Data ) {
   return $resource( Data.root_path + 'api/v1/careers/:id', { id: '@id'}, {
    query: {
        isArray: false,
        method: 'GET'
    }
   });
}]);


Career.query(function(res) {
   $scope.careers = res.careers.data;
}, function(error) {
  // Error handler code
}); 

答案 1 :(得分:2)

请参阅:http://docs.angularjs.org/api/ngResource。$ resource

$scope.init = function () {
    var success = function(careerList, getResponseHeaders){
      $scope.careers = careerList;
    };
    var failure = function(data){
      // TODO
    };
    Career.query(success, failure); 
};

由于这种怪癖和其他烦恼,我建议使用Restangular而不是默认的$ resource。它让生活更轻松