8

我有一個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(); 
    }; 
} 

在這裏,我有點糊塗了處理響應數據分配給範圍變量,現在我得到空數組[] in $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 = []; 
    }); 
}; 

使用$資源查看控制檯我的要求。

enter image description here

回答

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 
}); 
+0

謝謝,你節省了我的時間... – devo

+0

同樣在這裏一直在掙扎小時 – Awena

2

參見:http://docs.angularjs.org/api/ngResource $資源

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

由於這種怪癖和其他煩惱,我建議使用Restangular而不是默認的$資源。它使生活變得更輕鬆

+0

我的第一個問題,爲什麼我得到空數組[]在$ scope.careers? – devo

+0

不知道,它可能是發生故障時的默認值... – fabrizioM

+0

這不是失敗。看到屏幕截圖,我正在獲取所有值,如何將其映射到範圍變量? – devo