AngularJS, building a hash of resources

Is there a way, in an AngularJS controller, to take a URL and redirect that request to the best place for fetching JSON data? The VideoSearchCtrl is connected to the search form. Everything seems fine with the generated URL for the template, so I aim to use the controller to direct it to the appropriate location for fetching the JSON data.

GuideControllers.controller('VideoSearchCtrl', ['$scope', 'VideoSearch',
    function($scope, VideoSearch) {
        var pattern = new RegExp(".*/search\\?=(.*)");
        var params = pattern.exec( document.URL )[1];//redirect to videos to execute the search for the data
        $scope.videos = VideoSearch.query({ resource: "videos", action: "search", q: params });
    }
]);

This sends /videos/search?q=xyz into the query. The factory creates the resource:

var VideoSearchServices = angular.module('VideoSearchServices', ['ngResource']);

VideoSearchServices.factory('VideoSearch', ['$resource',
    function($resource){
        return $resource("/:resource/:action:params", {resource: "@resource", action: "@action", params: "@params"}, {
            query: {
                isArray: true,
                method: "GET",
                headers: {
                    "Accept": "application/json",
                    "X-Requested-With": "XMLHttpRequest"
                }
            }
        });
    }
]);

However, the server receives the URL as /videos/search%fq=xyz instead of /videos/search?q=xyz, resulting in the "show" method being called instead of a custom "search" action. It seems like there might be some issue with escaping characters or perhaps the "?" symbol is causing confusion in the resource factory. This could be obvious to someone experienced with AngularJS or JavaScript in general.

I already have a template for search and can successfully retrieve JSON from a different location. Both functionalities work independently, but I struggle to fetch the JSON using the provided code.

Answer №1

To start with, execute the following steps:

return $resource("/:resource/:action", {resource: "@resource", action: "@action"}, {

Afterwards:

$scope.videos = VideoSearch.query({ resource: "videos", action: "search", q: params });

The main idea here is that params should not be included in the url declaration for the resource. Instead, you only need to declare resource and action, and then you can add params as needed for all routes.

Answer №2

Utilizing $location from Angular and jQuery's extend is a more efficient way to handle this task, as it allows for seamless integration of any future parameters that may be added. Simply update the query factory with new params when needed.

GuideControllers.controller('VideoSearchCtrl', ['$scope', '$location', 'VideoSearch',
   function($scope, $location, VideoSearch) {
      var route = jQuery.extend(
         { resource: "videos", action: 'search' },
         $location.search()
      );
      $scope.videos = VideoSearch.query(route);
   }
]);

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

Navigating with AngularJS 1.6: Routing and More

As I set up the routing for my AngularJS v1.6 app, I encountered a small issue. An error message popped up and I can't seem to pinpoint the root cause. Can anyone provide insights on what might be causing this error? Uncaught Error: [$injector:modul ...

What is the fate of the code that comes after executing history. push in React?

My go-to for routing is typically the Redirect component. It's straightforward since you just need to return the Redirect component when needed. However, I'm a bit lost when it comes to using history objects. In my code base, after pushing a rout ...

jQuery UI tabs loaded with Ajax causing Javascript to malfunction

It appears that Javascript is disabled in jQuery UI tabs when loaded through ajax. Testing with jQuery tooltips and .click() alerts shows that Javascript functions properly in tabs not loaded through ajax (IDs present on the page). Below is the method use ...

What is the best way to utilize this resulting value as an input?

I am trying to generate a random number using math.random and use that value in the following script: let bday = Math.floor( Math.random() * (30 - 1 + 1) + 1 ); await test.page.select('select[name="day_select"]',bday); However, I am ...

Creating a Music Bingo game to ring in the New Year

Looking to create a Music Bingo game for New Year's Eve with randomized songs that can be selected, but experiencing an issue where nothing happens when you have 4 in a row. Attempted adding a submit button, but it doesn't trigger any action. Ide ...

Transform the year into the Buddhist calendar system

I recently started learning AngularJS and have a question. I am currently using Date.now() to get the current time, but I would like to display the year in Buddhist format. I came across a code snippet in this topic -> How to make a ticking clock (time) ...

Enable the jQuery UI Autocomplete feature with Google Places API to require selection and automatically clear the original input field when navigating with the

I am currently using a jquery ui autocomplete feature to fetch data from Google Places... The issue I am experiencing is that when the user navigates through the suggestions using the up and down arrows, the original input also appears at the end. I would ...

Display a div using ASP.NET when a button is clicked

I am currently attempting to display a loading div when a button is clicked, however, I am encountering some issues with the functionality. Javascript : <script type="text/javascript"> $(document).ready(function (e) { $(&a ...

Exploring a Ring with Three.js OrbitControls Rotation

I am having an issue with my OrbitControls camera setup. Currently, the camera rotates around a fixed point at player.position.x, y, and z coordinates. While it works fine, I need the camera to rotate around a ring instead. In the examples provided, the fi ...

Difficulty adapting CSS using JavaScript

I am looking to adjust the padding of my header to give it a sleeker appearance on the page. I attempted to achieve this with the code below, but it seems to have no effect: function openPage() { var i, el = document.getElementById('headbar' ...

The error message "no match found" can only occur on the server-side when using jQuery version 1.x

Having an issue with this small section of code: $('.desc_container').each(function() { var fulltext = $(this).text(); if(fulltext.length > 50) { var myRegexp = /^(.{47}\w*\W)(.*?)$/g; var match = myRegexp.exec(f ...

Creating a Parent Container to Maintain the Height of the Tallest Offspring

I've been searching online for solutions, but so far I haven't found one that meets all the requirements. <div class="parent"> <div class="child1">I am 60px tall and always visible; my parent is 100px tall</div> <div ...

Changing a class and audio and storing it using browser's local storage

The challenge I am facing: I am currently working on a feature for my website that allows users to toggle the volume on/off and have that setting persist across different pages. Specifically, I want the user's volume preference to be saved when they n ...

What are the best ways to improve ajax response in jQuery?

My database query is fetching around 5000 rows of data along with data from 5 relational tables, leading to performance issues. The network tab shows the size of the request resource as 9.1 mb. After that, I am dynamically adding this data to a table using ...

Ways to customize a directive to show conditionally with no need for container elements

I have created a basic role-based security directive in angularjs. It's my first attempt at making a directive. My goal is to replace the following HTML: <authorize if-granted="GET_POSTS"> Hello WORLD!!!! {{name}} </authorize> with j ...

How does the 'order' stack up against the 'products' array? Display the names of the products that are included in the order

I have an array of items for sale: const products = { { id: product1, name: 'Product A', price: 100 }, { id: product2, name: 'Product B', price: 200 }, { id: ...

Is it possible to use an Ajax callback function to add a select dropdown HTML to a table

I am currently in the process of using jQuery to append some HTML with the code provided below. My main objective is to select an option based on AJAX response data and create a select dropdown menu. However, the variable scope of sOut doesn't seem to ...

Steps to displaying the result

new Vue({ data: { folders : [{ name : 'folder1', isActive : 1, }, { name : 'folder2', isActive : 0, }, ] } } }) Is there a way to access the active val ...

Issue encountered when executing the migration fresh seed: SyntaxError, which indicates the absence of a closing parenthesis after the

Having trouble with a nextJS project that utilizes mikro-orm? Struggling to overcome this persistent error for days: C:\Users\BossTrails\Documents\core.nest-main_2\node_modules\.bin\mikro-orm:2 basedir=$(dirname "$(e ...

Having trouble with the Jquery animate() function?

I recently developed a jQuery animation where clicking on specific buttons triggers a hidden div to slide from left: -650px; to left: 0px;. You can see an example by clicking here. However, I've noticed that when another button is clicked to reveal a ...