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

What steps can be taken to choose a particular class when multiple classes share the same name?

Imagine having a table layout like this: <table class="first-table" border="1" width="400px"> <tr> <td><?php echo $row_cond['title']; ?></td> <td><a class="more" href="#" onClick="slideup() ...

Tips for passing a function to express-handlebars within a node.js-express application

I've been attempting to pass a function in express-handlebar, but for some reason it's not working. In my setup, I have app.js serving as the server file and index.handlebars as the handlebar file. In app.js: const express=require('expres ...

Elements vanish when SHAKE effect is in use

I've been experimenting with this framework and I'm struggling to get the shaking effect to work properly. Whenever I hover over an element, other divs seem to disappear. I tried using different versions of JQuery and JQuery UI on JSFiddle, and i ...

Issue with custom function not being triggered by datepicker onSelect in Internet Explorer with JQuery

I have a datepicker set up like this: $("#startDate").datepicker({ onSelect: changeDate }); This is used with the following input field: <input type="text" id="startDate" value="" class="dateField"/> This setup works well in Chrome, but encou ...

Can I send a DELETE request with request body and headers using Axios?

When working with Axios in ReactJS, I am attempting to send a DELETE request to my server. In order to do this, I need to include the following headers: headers: { 'Authorization': ... } The body of the request consists of: var payload = { ...

Having trouble accessing the text in a paragraph using JavaScript executor and web driver

On a particular website, there is: <p id="tempid" value="Manual Effect">testing the test</p> String value = (String)((JavascriptExecutor) this).executeScript("return window.document.getElementById('tempid').value"); System.out.pr ...

Adjust the navigation text and logo color as you scroll on the page

I am new to HTML and CSS and I am working on a website with PagePiling.js scrolling feature. I want to change the color of my logo image and navigation text dynamically as I scroll to the next section. Specifically, I only want the part of the logo and tex ...

Bidirectional communication between two AngularJS scopes or controllers utilizing a service

I am facing numerous situations where I require clicks or other interactions to trigger actions in a different area of the webpage (one-way communication). Now, I have encountered a need for bidirectional communication, where changes made in element A can ...

Iterate through a JavaScript array to access objects with varying IDs

Struggling to navigate the JSON data due to ID 29450 and 3000 out of a total of 1500 IDs in the database. Looking to log the information ['Id', 'Description', 'StartDate'] for both IDs. Feeling a bit stuck, hoping someone can ...

Setting up a local development environment for AngularJS

I have been using the boilerplate https://github.com/node90/angular-starter as a foundation for my projects. However, I've noticed that the repository utilizes gulp to consolidate the js files in the 'app' folder into the 'public/js&apo ...

The resize function fails to trigger when it is required

Struggling to get this code working properly. If the window width is greater than 800, I want 6 images with a red background. If the window width is less than 800, I want 4 images with a blue background. I need this functionality to work both on r ...

Does vuetify have a v-autocomplete callback for when there is no filtered data available?

Is there a method to detect when the v-autocomplete component in Vuetify.js displays "no data available" after filtering? I have searched the events documentation here https://vuetifyjs.com/en/api/v-autocomplete/#events Is there a workaround for this iss ...

What discrepancies exist between running npm install on Windows versus Linux operating systems?

Just have a quick question to ask. I've been searching online with no luck. If I were to run npm install on a Windows machine to set up my dependencies, would it be viable to transfer the node_modules directory to a Linux machine and execute my nodej ...

It is not possible to access fields in Firestore using Node.js

Exploring the limits of my Firestore database access with a test function: exports.testfunction = functions.https.onRequest(async (request, response) => { try{ const docRef = firestore.collection("Stocks").doc("Automobile" ...

display a new feature immediately upon the user's login

I encountered a scenario where the user is supposed to log in, and upon successful login, another component should be displayed. However, this functionality is not working as expected for me. I have to click the login button again or refresh the page to vi ...

Guide to using VueJS for sending a POST request with a JSON array containing data and uploading a File or Picture for each element in the array

I am currently facing a challenge with Axios where I need to send formData from a dynamic Form to PHP. Users should be able to add multiple "persons" along with their respective data and pictures. Below is the format of the data: data: { person:{ ...

Validation within nested Joi schemas

Need help validating a nested object conditionally based on a parent value. const schema = Joi.object({ a: Joi.string(), b: Joi.object({ c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Jo ...

Create a webpage in full screen mode with a video player that fills the entire screen

Here is the HTML code I am working with: <div id="container"> <video id="video" src="video.ogv" loop></video> </div> The "container" div and video element occupy the entire screen. #container { po ...

Creating dynamic HTML elements for each section using JavaScript

Is there a way to dynamically add a task (input + label) for each specific section/div when entering the name and pressing the "Add" button? I attempted to create an event for each button to add a task for the corresponding div of that particular section, ...

Verify the functionality of a specific method invoked within another method through unit testing

I currently have a method in my Angular application that is triggered upon clicking. Inside this method, I pass a value to another private method. .ts file public onViewItem(item: Results): void { const ids = [item.data['id']]; this.anot ...