Utilizing AngularJS: Techniques for Binding Data from Dynamic URLs

Just starting out with AngularJS

We are using REST APIs to access our data

/shop/2/mum  

This URL returns JSON which can be bound like so:

function ec2controller($scope, $http){
  $http.get("/shop/2/mum")
           .success(function(data){
                $scope.shopname = data.name;
                $scope.location = data.location;
                $scope.customer = data.customer;
    })

In the HTML:

<div class="shop">
  <ul class="list-group">
    <li class="list-group-item">
     <span class="shop-box">{{showname}}</span>
    </li>
    <li class="list-group-item">
     <span class="shop-box">{{location}]}</span>
    </li>
   </ul>
  </div>

Everything is working smoothly!

Now, we want a dynamic URL format:

/shop/<user-id>/<location>

I need to update this URL when selecting an option from a drop-down, and set the values in {{shopname}}, {{location}} accordingly. Can someone help me with this?

Thank you

Answer №1

Your app.js should include a list of routes that ui-router is aware of, some of which may have dynamic components. To achieve this in your scenario, you would need to implement something similar to the code below:

$stateProvider.state('store', {
    url:"store",
    abstract: true,
    views: {
        "body": {
            templateUrl: "partials/store.html",
            controller: "StoreController"
        }
    }
})
.state('store.customer', {
    url: "/:customer",
    views: {
        "body": {
            templateUrl: "partials/store.customer.html",
            controller: "StoreCustomerController"
        }
    }
})
.state('store.customer.location', {
    url: "/:location",
    views: {
        "body": {
            templateUrl: "partials/store.customer.location.html",
            controller: "StoreCustomerLocationController"
        }
    }
})

Keep in mind that the /store route is defined as an abstract, meaning it won't be resolved directly. If you want /store/2 to behave similarly, follow the same structure.

In the ShopCustomerLocationController, for instance, you can retrieve the URL parameters like this:

$state.params.location; // returns "mum"
$state.params.customer; // returns "2" <-- note that it's a string, not an integer

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

"Although all error messages are functional in Postman, they are not appearing correctly on the frontend client

I am currently developing a website using React and Node. While testing my register and login functionality in Postman, I encountered an issue where the error message for login (e.g., user doesn't exist, username or password incorrect) is not displayi ...

How can I make AWS SDK wait for an asynchronous call to finish executing?

Understanding the AWS SDK documentation can be a bit confusing when it comes to making asynchronous service calls synchronous. The page at https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html states: All ...

Establishing a bidirectional binding directive attribute within an AngularJS HTML structure

I'm new to AngularJs and I've encountered a problem that might be due to my lack of understanding about directives, controllers, and isolated scopes. I'm trying to figure out how to set a directive attribute to true/false in the html and kee ...

How to Send jQuery ajax Requests with Multiple Buttons in a PHP Form

My current issue is as follows: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <body> <form id="roomform" action="room.php" method="POST"> <b ...

Why does one of the two similar javascript functions work while the other one fails to execute?

As a new Javascript learner, I am struggling to make some basic code work. I managed to successfully test a snippet that changes text color from blue to red to ensure that Javascript is functioning on the page. However, my second code attempt aims to togg ...

Is there a way to conceal JavaScript code?

I am trying to keep my AJAX code hidden from users who view the source of my PHP page. How can I achieve this? Below is the AJAX code that I currently have: <script type="text/javascript"> function Ajax(){ var xmlHttp; try{ xmlHttp=n ...

Expand the accordion to reveal all the content

I'm facing an issue with my accordion where a scrollbar appears in every content section. To fix this, I tried setting overflow: hidden in the CSS: .ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: hidd ...

Is there a method to stop react-select (Select.Async) from erasing the search input value when it loses focus?

Situation: In my setup, I have a standard select element (categories), which dictates the options displayed in a Select.Async component from react-select. Problem: Consider this scenario: a user is searching for an option within Select.Async whil ...

Hiding Bootstrap Popover When User Clicks Outside of it

My webpage has dynamically loaded content featuring popovers which need to be bound to the body for correct loading and appearance. I am looking for a solution to hide the popovers when a user clicks outside them or on another popover trigger. After some ...

Display a page with sections that have opacity applied, identified by the hashtag #section, and utilize JavaScript to automatically scroll to the top of

Check out my app at . I'm working on overriding the scroll bar behavior in CSS to keep the entire app visible, including the logo, header, and controls, as users navigate through different sections. However, I seem to be having trouble with the CSS as ...

Window backdrop being filled

I am attempting to set a background image that fills the entire window regardless of its size. I have implemented html, css and script as shown below: // Function adaptImage() // Parameters: targetimg function adaptImage(targetimg) { var wheight = $ ...

Exploring AngularJS: utilizing ngIf and ngRepeat

Currently, I am utilizing ngRepeat and ngIf to filter and sort some data. Initially, I pondered using ngSwitch instead of ngIf for this task, but struggled to find a suitable example. After experimenting with the slightly more complex ngSwitch, I opted to ...

Angular2: The comeback of accessing a getter after the service constructor has completed (using HTTP Get)

I have a requirement for my app where I need to utilize List.json to create a list, which forms the core of my application. To ensure this list is shared across all components, I have opted to establish a service. Within this service, I call my JSON file ...

Keystroke to activate Ant Design Select and start searching

I'm currently using the 'react-hotkeys-hook' library and have successfully implemented a hotkey that logs in the console when triggered (via onFocus()). My goal now is to use a hotkey that will open a Select component and add the cursor to i ...

transferring a delicious cookie to the browser

I have successfully integrated a basic login system using angular, express, and passport.js into an existing project by following the file structure and coding standards provided in angular-passport. Currently, users can sign up and log in without any iss ...

Error: Unable to return callback response from NodeJs function

I have a function that handles the process of reading a private key from the filesystem and generating a JWT token. The code successfully reads the file and creates a token, but it encounters an issue when attempting to callback to the calling function. De ...

Eliminating an SVG component from the webpage with the help of jQuery

Utilizing jQuery to insert an element into an embedded SVG can be achieved with the following code: var rect = SVG('rect'); $(rect).attr( { x: left, y: top, width: right - lef ...

Is there a way to extract the numerical value from a string within an ID of a div and transform the rest of the string into a variable?

Looking to extract the final id of a div and convert it to a variable. <div class="margin_bot" id="itemRows2"> <p id="rowNum1">...</p> <p id="rowNum2">...</p> <p id="rowNum3">...</p> <p id="rowNum4"> ...

Can you explain the purpose and functionality of the 'next' parameter within a middleware function in the Node.js Express framework?

Currently, I am working on Nodejs with the use of "Express js". My focus is on the implementation of "middleware functions," and here is a snippet of my existing code: const express = require('express') const app = express() ...

Ensuring validity using dynamic context objects within Joi

I need to implement a dynamic validation system that involves downloading an object at runtime and saving it as a well-formed .json file. The objective is to use the values from this downloaded object as part of a validation process using Joi.validate wi ...