I'm trying to pick up angular.js
and working on figuring out some of the things that are a bit less documented.
Consider this - I have a search method on the server that accepts query params and returns a collection of search results, and responds to GET /search.json
route (Rails FWIW).
So with jQuery
, a sample query would look like this:
$.getJSON('/search', { q: "javascript", limit: 10 }, function(resp) {
// resp is an array of objects: [ { ... }, { ... }, ... ]
});
I'm trying implement this using angular, and wrap my head around how it works. This is what I have now:
var app = angular.module('searchApp', ['ngResource']);
app.controller('SearchController', ['$scope', '$resource', function($scope, $resource){
$scope.search = function() {
var Search = $resource('/search.json');
Search.query({ q: "javascript", limit: 10 }, function(resp){
// I expected resp be the same as before, i.e
// an array of Resource objects: [ { ... }, { ... }, ... ]
});
}
}]);
And in the view:
<body ng-app="searchApp">
...
<div ng-controller="SearchController">
...
<form ng-submit="search()">...</form>
...
</div>
</body>
However, I keep getting errors like TypeError: Object #<Resource> has no method 'push'
and $apply already in progress
.
Things seem to work out as expected if I change the $resource
initialization to the following:
var Search = $resource("/search.json?" + $.param({ q: "javascript", limit: 10 }));
Search.query(function(resp){ ... });
It seems more intuitive to initialize the $resource
once and then pass different query parameters with changes in the requested search. I wonder if I'm doing it wrong (most likely) or just misunderstood the docs that calling $resource.query
with the query params object as the first argument is feasible. thanks.
var Search = $resource(...)
beforehand not do the trick? I suppose I'm still working out the idea of services and factories in angular. Also, my first try was with$http
and it worked fine. I wanted to try out$resource
as well, just to get a feel for using either. Thanks! – Abram