1

这是一个真正的新手问题:

我在 erb 的 Rails 中查看了我的索引:

<div ng-app="Donor">
  <div ng-controller="DonorCtrl">

    <ul>
     <li ng-repeat="donor in donors">
      {{donor}}
    </li>
    </ul>

</div>
</div>

我从 Rails 返回的 Donor json 是:

class DonorSerializer < ActiveModel::Serializer
  attributes :id, :tools_id, :first_name, :last_name
end

我的javascript文件有这个;

var app;

app = angular.module("Donor", ["ngResource"]);

    // separate view to Add new donors

 $scope.addDonor = function() {
   var donor;
   donor = Entry.save($scope.newDonor);
   $scope.donors.push(entry);
   return $scope.newDonor = {};
 };

 $scope.showDonors = function() {
  var Donor = $resource("/donors", {
    update: {
        method: "GET"
    }
 });
 return $scope.donors = Donor;

}

this.DonorCtrl = function($scope, $resource) {
  var Donor;
  Donor = $resource("/donors/:id", {
    id: "@id"
}, {
    update: {
        method: "PUT"
    }
});
return $scope.donors = Donor.query();
};

如何在我的索引视图中获取捐赠者列表?

我错过了一些东西

4

1 回答 1

1

您的第一个问题是控制器内部没有正确的代码。我还把你的 $resource 变成了工厂的。我将 Donors 更新方法更改为“PUT”,因为您有一个“addDonor”方法。

确保您还为 angularjs 设置了正确的库。为此,您将需要:

angular.js
angular-resource.js

修改后的 Javascript:

var app;

app = angular.module("Donor", ["ngResource"]);

app.factory("Donors", [
  "$resource", function($resource) {
    return $resource("/donors", {}, {
      update: {
        method: "PUT"
      }
    });
  }
]);

app.factory("Donor", [
  "$resource", function($resource) {
    return $resource("/donors/:id", {
      id: "@id"
    }, {
      update: {
        method: "GET"
      }
    });
  }
]);

this.DonorCtrl = [
  "$scope", "Donor", "Donors", function($scope, Donor, Donors) {
    var donor;
    $scope.donor = Donor.query();
    $scope.donors = Donors.query();
    $scope.addDonor = function() {};
    donor = Donor.save($scope.newDonor)(function() {
      return $scope.donors.push(donor);
    });
    return $scope.newDonor = {};
  }
];

由于您使用的是 rails,这里是咖啡脚本版本(我发现它与 angularjs 结合起来很优雅):

app = angular.module("Donor", ["ngResource"])

app.factory "Donors", ["$resource", ($resource) ->
    $resource("/donors", {}, {update: {method: "PUT"}})
]
app.factory "Donor", ["$resource", ($resource) ->
    $resource("/donors/:id", {id: "@id"}, {update: {method: "GET"}})
]

@DonorCtrl = ["$scope", "Donor", "Donors", ($scope, Donor, Donors) ->
  $scope.donor = Donor.query()
  $scope.donors = Donors.query()

  $scope.addDonor = ->
        donor = Donor.save($scope.newDonor) ->
            $scope.donors.push donor
        $scope.newDonor = {}
]

我会查看 EggHead.io以更好地了解如何设置您的 Angular javascript 文件。

于 2013-03-22T16:38:50.473 回答