What is the best way to include parameters when calling $resource.query in AngularJS?

Currently, the url localhost/view/titles is set up to use the specific route, controller, and service described below. When accessed, the server will return a list of all title objects. How can the service be expanded to accommodate additional query parameters, such as a result limit?

// AngularJS app module with route configuration
var app = angular.module('app', ['ngResource']).
    config(function ($routeProvider, $locationProvider) {
        $routeProvider.when(
            '/view/:obj/:limit',
            {
                templateUrl: '/static/templates/titles.html',
                controller: 'titlesController'
            }
        )})

// List service definition
var listService = app.factory('listService', function ($q, $resource) {
        return {
            getList: function (obj) {
                var deferred = $q.defer();

                $resource('/api/view/' + obj).query(
                    function (response) {
                        console.log('Request successful')
                        deferred.resolve(response);
                    },
                    function (response) {
                        console.log('Request failed with status: ' + response.status)
                        deferred.reject(response);
                    }
                )
                return deferred.promise;
            }
        }
    }
)

// Controller definition
var titlesController = bang.controller('titlesController', function($scope, listService, $routeParams){
    $scope.titles = listService.getList($routeParams.obj);
})

Answer №1

Here is an example of code snippet:

angular.module('phonecatServices', ['ngResource']).
    factory('Phone', function($resource){
  return $resource('phones/:phoneId.json', {}, {
    query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
  });
});

Answer №2

If you're wondering how to send parameters to your backend API using a query string with the ngResource module, look no further. Here are the step-by-step instructions you need:

Setting up ngResource: First, install the ngResource package using bower or npm by running bower install angular-resource.

Next, add the angular-resource script to the head element of your index.html page:

<script src="lib/angular-resource/angular-resource.min.js"></script>

In your js/app.js file, include ngResource as a dependency in your module:

angular.module('app', ['app.controllers', 'app.services', 'ngResource'])

For the view (templates/list.html), here's an example of how to set up a search feature:

<input type="search" ng-model="filters.title" placeholder="Search">
<button ng-click="searchList(filters)">Submit</button>

<div ng-repeat="item in list">
  <p>{{item.title}} - {{item.description}}</p>
</div>

In the controller (js/controllers.js), here's how you can handle the search function:

.controller('ListCtrl', function($scope, ListService) {
  $scope.searchList = function(filters){
    $scope.filters = { title: '' }; //Clear the search box
    $scope.list = ListService.query({title: filters.title});   
  }
})

Lastly, in the factory (js/services.js), set up your ListService to make API calls:

.factory('ListService', function($resource) {
  return $resource('http://localhost:3000/api/view/:id', { id: '@id' });
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Service Worker's fetch event is not triggered upon registering the service worker

Service Worker is a new concept to me. As I delved into learning how to incorporate Service Worker into My Next.js Application, I encountered an issue with the fetch event handler. Oddly enough, the fetch event handler doesn't trigger upon initially r ...

The Javascript Switch statement is experiencing some functional issues

I am facing an issue where I need to handle different scenarios based on a decimal value, and I thought of using a Switch/case statement for this purpose. However, the code is not working as expected. Below is the snippet of code in question: var spread ...

Using the React Hook useCallback with no dependencies

Is it beneficial to utilize useCallback without dependencies for straightforward event handlers? Take, for instance: const MyComponent = React.memo(() => { const handleClick = useCallback(() => { console.log('clicked'); }, []); ...

What is the best way to access the second array in a JSON object?

I have successfully implemented autocomplete with JSON and PHP. It is working fine, but now I am facing a challenge in retrieving the second array from the JSON data. Below is the script I have used in source.php: <?php $req = "SELECT namaBarang, har ...

Is there a way to eliminate duplicates from an array in JavaScript by utilizing a set and placing each element in an li tag? Here is the code

const numbers = [" 4", "9", "16"," 4", "9", "16"," 4", "9", "16"] <ul> {(<li> {[...new Set(numbers)]} </li>)} </ul> const numbers = [" 4", "9", "16"," 4", "9", "16"," ...

Tips on converting comma-separated values into HTML table rows using <tr> tags

JSON Data { "catalog_name": ["Sistem Autodownline ", "Karipap Pusing Ayu"], "price": ["100", "8"], "qty": "", "qty2": ["", ""], "total_qty": "", "total": "", "mem": "10", "email_2": "", "ic_add": "890527-08-6136", "c ...

Defaulting to "Select All" as the initial value in ng-dropdown-multiselect

Below is some AngularJS code embedded in the view: <div class="icon-dropdown people-icon fixed-height-select" ng-dropdown-multiselect="" options="vm.collectionGroups" selected-model="vm.selectedCollections" ng-click="vm.events.getStatistics()"></ ...

Bind event listener exclusively for click event handlers

I have a scenario where I am using 'addEventListener' to handle the opening of a menu (genres-container) only after the transition on another menu (mobile-nav) has completed. The issue I am facing is that even after closing everything and trying ...

Ways to incorporate ng-app into an HTML element when HTML access is limited

In my current project, I am using Angular.js within a template system. The challenge I am facing is that I need to add ng-app to the html element, but I do not have direct access to do this on the page itself. Initially, my page structure looks like this: ...

Adding a badge to a div in Angular 6: What you need to know!

How can I add a badge to a specific div in Angular 6? I have dynamic div elements in my HTML. I want to increase the counter for a specific div only, rather than increasing it for all divs at once. For example, I have five divs with IDs div1, div2, div3, ...

Using ng-class to insert variable strings for dynamic styling

I'm currently working on a project where JSON data is used to generate custom forms. I've encountered an issue while trying to add validation to text inputs in the rendered forms. It seems simple enough, but I'm struggling with correctly ren ...

Click on a plane within a three.js environment to determine the X Y position within it

When using a raycaster, I can successfully obtain the current object (in this case, a plane) under the mouse. However, I am seeking a more precise X and Y value for the mouse position INSIDE the plane. var vector = new THREE.Vector3( ( event.clientX / win ...

Spacing issues with inline-block elements when dealing with a large quantity of items

Currently, I am tackling the JS/jQuery Project for The Odin Project and I am confident that my solution is working exceptionally well. However, the issue I am facing is that when dealing with larger amounts of elements (around 40-45 in JSFiddle and 50-52 ...

Handlebars template engine does not support query parameters

Below is the code snippet I am working with: app.get("/editar-equipo?:id", (req, res) => { const equipos = obtenerEquipos() let equipoSeleccionado for(let i = 0; i < equipos.length; i++){ if(equipos[i].numeroId === ...

Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object: const duplicate = {...original} You can also clone and update properties like this: const updatedDuplicate = {...original, property: 'value'} For instance, consider the foll ...

What is the process for implementing the sticky table header jQuery plugin?

I am looking to implement a sticky header on all tables in my web application, which is built on PHP. As the amount of data continues to grow, search results are fetching more records that may not be visible. I am primarily a PHP programmer and do not have ...

Error: EsLint detected that the classname is not a valid Tailwind CSS class

I am encountering an EsLint error indicating that "className is not a TailwindCSS class" after incorporating custom classes like colors into my tailwind.config.js file. Despite this, I am unsure about how to resolve this issue. Shouldn't EsLint recogn ...

What steps should I take to ensure that the login page functions properly?

Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Pag ...

Capture the height values from various divs and store them in an array, then utilize these values to adjust the size of other

My goal is to achieve the following: (1) Collect heights from multiple divs and store them in an array. (2) Apply these heights to other elements. The first element should receive the first value, the second element should receive the second value of the ...

What is the function of the next and back buttons in AngularJS?

I need assistance with creating next and previous buttons in Angular. As I am new to programming, I have written a program that works when using a custom array $scope.data = []. However, it doesn't work when I use $http and I would appreciate any help ...