8

I have a RESTful application with Laravel 4 and Angular JS.

In my Laravel Controller,

public function index() {

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

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

And the angular script,

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(); 
    };
}

Here I am little confused to handle the response data to assign to scope variable, now I am getting empty array [] in $scope.careers. And also How can I handle success and error to show some messages like the following normal $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 = [];
    });
};

See my request in console using $resource.

enter image description here

4

2 回答 2

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
}); 
于 2013-11-05T07:17:03.223 回答
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 。它让生活更轻松

于 2013-11-01T03:59:50.547 回答