这是一个真正的新手问题:
我在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();
};
如何在索引视图中获取捐赠者列表?
我错过了什么
答案 0 :(得分:1)
您的首要问题之一是您在控制器内部没有正确的代码。我还将您的资源转入了工厂。我将Donors更新方法更改为&#39; PUT&#39;因为你有一个'addDonor&#39;方法
确保您还为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,这里是coffeescript版本(我发现它与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以便更好地了解如何设置角度javascript文件。