Retrieve all scope variables included in the query parameters

Looking to extract variables from the URL and assign them to scope variables. The URL format might be altered, but for example:

http://example.com?opt.val=true&eg=foobar

The controller code in consideration is as follows:

m.controller('maps', function ($scope) {
    $scope.opts = {
        val: false,
        lav: false
    };
    $scope.eg = "Hello, World!";
});

The goal is to extract opt.val=true&eg=foobar from the URL and set the respective controller variables accordingly:

$scope.opt.val = true;
$scope.eg      = "foobar";
$scope.lav     = false;

Seeking an efficient method using Angular or any better alternative instead of resorting to parsing and manually assigning each variable in the scope. Any suggestions?


If further clarification is needed, feel free to request more information.

Answer №1

To start off, you can easily retrieve the values using the $location service

var search = $location.search();
// should be similar to
// {
//     "opt.val": "true",
//     "eg": "foobar"
// }

Then, utilize the $parse service to set the values to your $scope

angular.forEach(search, function(val, key) {
    $parse(key).assign($scope, val);
});

Remember that all values in $location.search() are strings, including "true" and "false", so you might need additional logic to handle these if you require Boolean values. Consider something like this

angular.forEach(search, function(val, key) {
    var evaluated = $scope.$eval(val);
    if (evaluated !== undefined) {
        val = evaluated;
    }
    $parse(key).assign($scope, val);
});

Check out a Plunker demo here: http://plnkr.co/edit/xOnDdWUW8PgsMFgmXr0r?p=preview

Answer №2

Here are a few ways you can achieve that:

#1 Utilizing $StateParams

If you are working with angular's URL Routing, you have the option to utilize $stateParams which provides the desired output. Simply define your parameters within your Router. For instance:

$stateProvider
.state('contacts.detail', {
    url: "/contacts?myParam&myParam2",
    templateUrl: 'contacts.detail.html',
    controller: function ($stateParams) {
        // When navigating from /contacts/42
        expect($stateParams).toBe({contactId: "42"});
    }
})

This sets up your route contacts to receive myParam and myParam2. Subsequently, you can easily parse these parameters in your controller using $stateParamsService:

controller: function($stateParams){
  $stateParams.myParam //*** Accessible! ***//
 }

#2 Leveraging $location

If you're not utilizing routes and prefer a more low-level approach, you can inject $location into your controller and service to extract the queries, like so:

var paramValue = $location.search().myParam; 

Do note that enabling html5mode is essential for it to work:

$locationProvider.html5Mode(true);

Trust this information proves beneficial.

Answer №3

To implement the Angular way, simply inject $routeParams into your controller.

Take a look at the example below

// Example:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Result:
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}

For further information, check out $routeParams documentation

Answer №4

If you're looking for a handy tool, consider checking out url.js. Here's a useful example:

url.parse("http://example.com?opt.val=true&eg=foobar").get.eg === "foobar"

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

Sending files correctly using Node.js

Here is a simple middleware to consider: (req, res, next) => { const stream = fs.createReadStream(req.filePath) await new Promise((resolve, reject) => stream .on('error', reject) .on('end', resolve) .pipe(res ...

Managing multiple input fields with React Hooks

Over at the React documentation forms section, you'll find an example that utilizes class components like so: class Reservation extends React.Component { constructor(props) { super(props); this.state = { isGoing: true, numberOfGu ...

Streamline the testing process to ensure compatibility with jQuery version 2.x

I currently have a substantial JavaScript code base that is all built on jQuery 1.8. I am planning to upgrade to jQuery 2.1 in the near future and I am fully aware that many parts of my code will likely break during this process. Is there any efficient me ...

Releasing an ASP.NET CORE web application with AngularJS on IIS

In the process of developing a new asp.net core web app (using the full .net framework) with AngularJS version 1.5.8, we have encountered an issue. Our app is currently very basic, consisting of just one page displaying student data in a table. When runn ...

Enhance your webpage with personalized designs and track the innerHTML elements

Creating a unique CSS style, such as <special> </special>, is my current task. special { color: #000000; background: #ffff00; } I want to apply this style using innerHTML in Angular. However, it seems challenging due to the Sanitizatio ...

Using Ajax, jQuery, and PHP to upload images along with additional data

I am currently facing an issue while trying to upload data along with an image using ajax and php. Whenever I include the line of code dataResult.file = form_data;, I receive an error message saying "illegal invocation". Please refer to the code snippet be ...

Contrasting the addition of an onClick listener through Jquery versus utilizing an HTML onclick attribute

I found this interesting piece of code that I want to share with you all: <!DOCTYPE html> <html> <head> <script type="text/javascript" src="jquery-1.12.4.js"></script> <title> HelloWorld JQuery </t ...

Creating an HTML element for every ajax response

I am currently working on a simple ajax call that updates a div with HTML formatting. However, I need to trigger the ajax call every 3 seconds to bring in updated responses. Should I restructure each time or is there a way to combine the HTML for each resp ...

Is AJAX causing issues with my media uploader and color picker?

Currently, I have incorporated tabbed navigation within a WordPress admin page and it is functioning properly on its own (data can be saved). However, I am now looking to implement some AJAX functionality for toggling between pages. The issue arises when t ...

On click, triggering the class "animate__animated animate__bounce" to activate

Just starting to learn html and css and came across this awesome library: Here's the code snippet I have so far: <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.mi ...

Issue with Firefox browser: Arrow keys do not function properly for input tags in Twitter Bootstrap drop down menu

Requirement I need to include a login form inside the dropdown menu with username and password fields. Everything is working fine, except for one issue: Issue When typing, I am unable to use the arrow keys (up/down) in Firefox. This functionality works ...

Troubleshooting Problem with UI-Grid Data Presentation

I am currently utilizing ui-grid in my Cordova application. However, I have encountered an issue where the data is sometimes displaying on the left side, as shown below: https://i.sstatic.net/SmBIb.png Do you have any suggestions to fix this? HTML < ...

Is there a way to create a universal script that works for all modal windows?

I have a dozen images on the page, each opening a modal when clicked. Currently, I've created a separate script for each modal. How can I consolidate these scripts into one for all modals? <!-- 1 Modal--> <div class="gallery_product col-lg-3 ...

Is it advisable to send an object as an argument in a function?

Here's the code snippet I'm working with: const failure1 = false; const failure2 = false; function callbackFunction(callback, errorCallback) { if (failure1) { errorCallback({ name: 'Negative event1 occurred', ...

Switch from using a select tag to a check box to easily switch between a dark and light theme

I have implemented a feature on my website that allows users to toggle between dark and light themes using the select tag with jQuery. Here is the code snippet that I am currently using: $(function() { // Code for changing stylesheets based on select ...

Angular controller fails to fetch scope variable in subsequent view

I'm currently working on implementing a login feature that directs a validated user to a personalized HTML view that greets them with their name. The initial view is a login page. When the user clicks the "Log In" button, the ng-click function is sup ...

AngularJS deferred queue with $q

Suppose I have an array representing a queue of files in the following format: [{deferred: fileDef, data: file}, {...}, ...] Each fileDef and file are sent to an upload function which returns fileDef.promise and calls fileDef.resolve or fileDef.reject af ...

Utilizing a combination of Infinite Scroll, Isotope, and Firebase Firestore for seamless pagination functionality

Just starting out in the world of web development. Any help is appreciated! I'm attempting to showcase items stored in Firestore by utilizing paginate queries. The aim is for each time a user reaches the bottom of the page, we trigger a call to Fires ...

Google Map continues to update itself without needing to call render() again

In my current project, I am integrating Google Maps using ReactJS and Redux. However, whenever I interact with the map like clicking on a marker or zooming in, the entire map refreshes and turns gray before redrawing the same map with the marker. Even aft ...

Discovering a locator based on the initial portion of its value

Here's a piece of code that is used to click on a specific locator: await page.locator('#react-select-4-option-0').click(); Is there a way to click on a locator based on only the initial part of the code, like this: await page.locator(&apos ...