This is a real newbie question:
I have a view for my index in Rails in erb:
<div ng-app="Donor">
<div ng-controller="DonorCtrl">
<ul>
<li ng-repeat="donor in donors">
{{donor}}
</li>
</ul>
</div>
</div>
my Donor json returned from Rails is:
class DonorSerializer < ActiveModel::Serializer
attributes :id, :tools_id, :first_name, :last_name
end
My javascript file has this;
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();
};
How do I get a list of donors to in my index view?
I am missing something
One of your first issues was that you did not have the right code inside of the controller. I also turned your $resource's into factory's. I changed the Donors update method to 'PUT' since you have an 'addDonor' method.
Make sure you also have the proper libraries setup for angularjs. For this you will need:
angular.js
angular-resource.js
The altered 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 = {};
}
];
Since you are using rails, here is the coffeescript version (I find it elegant in combination with 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 = {}
]
I would checkout EggHead.io for a better understanding of how to setup your angular javascript files.