Restangular JSON vs. JSON作为对象 - 在控制器中使用$ filter不能与restangularized一起使用

时间:2014-01-03 11:49:07

标签: javascript json angularjs restangular

我使用Restangular时遇到问题。

在我的Controller中,我读了一个JSON文件并用ng-repeat显示它。 我使用$ filter做一些预过滤只显示某些结果。

然而,我尝试了一个演示应用程序,它使用Restangular从json文件中获取JSON。 在不使用$ filter的情况下显示整个JSON。但是当应用$ filter时,我没有得到任何结果。似乎Restangular修改我的JSON所以我的过滤器将无法工作。 这可能是解决方案,但我不知道在哪里将它放在我的Restangular设置中。我是一个新手,所以要善待我;)https://github.com/mgonto/restangular/tree/master#how-can-i-access-the-unrestangularized-element-as-well-as-the-restangularized-one

我的代码如下:

 myApp.controller('IndexCtrl', function ($scope, $filter, myRestangular) {

// Helper function for opening new webviews


  // Fetch all objects from the local JSON (see app/models/model.js)
  $scope.items = myRestangular.all('item').getList();


 // Same JSON Object
    //   $scope.items = [
    //   {
    //     "app_id": 1,
    //     "place": "Canada",
    //     "name": " Toronto",
    //     "age": " 1",
    //     "description": "Just testing."
    //   },
         ......//other data
    // ];

  // MY Filter to display all entries with place Canada, works with JSON embeded into   the script, but not with the restangular one 

   $scope.items = $filter("filter")($scope.items, {place: "Canada"});


});

模型

var module = angular.module('AppModel', ['restangular']);

module.factory('myRestangular', function(Restangular) {

  return Restangular.withConfig(function(RestangularConfigurer) {

    RestangularConfigurer.setBaseUrl('http://localhost/data');
    RestangularConfigurer.setRequestSuffix('.json');

    RestangularConfigurer.setRestangularFields({
      id: "app_id"

    });

  });


});

要获得单个元素,这也适用。

// Fetch all objects from the local JSON (see app/models/model.js)
  myRestangular.all('item').getList().then( function(items) {
    // Then select the one based on the view's id query parameter
    $scope.item = $filter('filter')(items, {app_id: 1})[0];

  });

1 个答案:

答案 0 :(得分:1)

我不是Restangular用户,但由于AJAX调用是异步的,因此当你调用$scope.items = $filter("filter")时,没有什么可以过滤的。

您已经注意到它适用于.then( function(items) {,因为到那时您已收到回复。