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.
because you have not defined a resources with the name Search. First you need to define such a resource. Doc: $resource. Here is an example implementation
Include this module in you app and use it in a controller like this
However I am not sure if this is what you need. The resource service interacts with RESTful server-side data sources aka REST API.
Maybe you need just a simple http get:
http://docs.angularjs.org/api/ng.$http