Tips for accessing id from $http.get in angular.js

Hello everyone, I'm new to Angular.js and currently learning it. I need help in retrieving data from the following API URL: . I am unsure how to implement this in my controller.js file. Below is the code I have so far, can someone please guide me on how to fetch the data of the business with id=36?

var reControllers = angular.module('reControllers',[]);
reControllers.controller('RecentController', ['$scope','$http' ,function($scope,$http){
    $http.get('http://ba.dev/businesses/businesses').success(function(data){
        $scope.business = data;
     }); 
}]);

reControllers.controller('PageController', ['$scope','$http', '$routeParams' ,function($scope,$http,$routeParams){
    $http.get('http://ba.dev/businesses/businesspage').success(function(data){
        $scope.student = data;
        $scope.whichItem = $routeParams.itemId; 
    }); 
}]);

Below is my app.js file

var myApp = angular.module('myApp',[
    'ngRoute',                                
    'reControllers'                   
]);

myApp.config(['$routeProvider', function($routeProvider){   
    $routeProvider.                      
        when('/main',{               
        templateUrl : 'partials/main.html',
        controller : 'RecentController'
    }).
    when('/page/:itemId',{
        templateUrl : 'partials/page.html',
        controller  : 'PageController'
    }).
    otherwise({                   
        redirectTo: '/main'   
    });
}]);     

Answer №1

Extract the ID from the URL by utilizing the $routeParams function.

$http.get('http://ba.dev/businesses/businesspage/' + $routeParams.itemId)

Next, incorporate server-side logic to retrieve the passed itemId from the URL. Execute necessary operations to fetch data from the database and send it back as a response.

Answer №2

It is suggested to utilize then over success as the latter is deprecated. Therefore, your code should look like this:

$http.get('http://ba.dev/businesses/businesses').then(function(data){
 $scope.business = data;
 }); }]);.....

The AngularJS documentation provides the following example for a simple GET request:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

For more information on route parameters, refer to: AngularJS $routeParams

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

The URI entered is not valid: The parsing of the hostname failed. Electron Builder

Having an issue while trying to build an electron app using squirrel, even though the iconUrl is valid. Here is my package.json configuration: "squirrelWindows": { "iconUrl": "http://95.85.39.111:5005/skylog.ico" }, Error message received: An unhand ...

jQuery: use the "data-target" attribute to toggle the display of a single content area

My code generally works, but there is an issue. When clicking on "Link 1" followed by "Link 2", only the content for Link 2 should be visible. How can I achieve this with my code? $("li").click(function() { $($(this).data("target")).toggle(); // ...

Ensure that the dropdown menu remains visible even after the mouse no longer hovers over it

Looking to create a main menu with dropdown items that appear when the user hovers over them? You may have noticed that typically, the dropdown disappears once the hover event is lost. But what if you want the menu to stay visible and only disappear upon c ...

Monitor elements in real-time as they are inserted into the DOM using a Chrome Extension

In the process of developing a Chrome extension, I am tackling the task of removing or hiding specific elements based on their id/class. While accomplishing this after the DOM is loaded poses no issue, it does result in a noticeable "blink" on the page dur ...

In Pure JavaScript, an HTML element is added every time the click event is triggered

Hey everyone, I'm facing a small issue and I could use some help fixing it. I need to implement an onclick event that adds HTML code every time it's clicked. I am hesitant to use innerHTML due to its potential risks. Here is the code snippet: bu ...

Stopping npm private organization from releasing public packages

Is there a method to restrict the publication of public packages within an npm organization? It appears that this scenario would often arise (ensuring that no member of an organization accidentally publishes a package as public when it should be private b ...

Tips for aligning an element vertically when it has a float using CSS or JavaScript

I am struggling with centering the image within the article list loop I created. The code snippet looks like this: <article class="article <?php if($i%2==0) { echo 'even'; } else { echo 'odd'; } ?>"> <section class ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

How to eliminate a hyperlink from an HTML element with the help of JQuery

Recently, I was assigned to revamp a website for the company I work for. However, upon closer inspection, I realized that the website is quite messy and relies heavily on templates, resulting in certain elements being auto-generated as active links. The i ...

I need to implement a div-based dropdown with a scrollbar in JavaScript and CSS to prevent it from extending beyond the screen. Additionally, the use of struts is essential in this implementation

Dealing with a dynamically populated div-based dropdown can be tricky, especially when it extends beyond the screen's limits and hides entries. This is an inherited application that lacks support, leaving me to handle it without the necessary expertis ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

ReactJs Unicode Integration with ID3 JS

I am working on a React Project that involves using an input type = "file" to upload music files. I am able to extract tags using ID3 Js, but the result is displayed in this format: https://i.stack.imgur.com/192co.png Is there a way to convert ...

Is there a way to conceal a component using Twitter Bootstrap while having the ability to reveal it with the help of

Suppose I generate an HTML element in the following manner, <div id="unique-div" class="concealed">Hello, TB3</div> <div id="unique-div" class="hide-me">Greetings, TB4</div> <div id="u ...

The challenge with encoding URL in Ajax requests

I am trying to send an encrypted message along with the corresponding key (two-way encryption) to a PHP page for decryption, and then receive the decrypted result in the response. Below is an example of how I am attempting to send the encrypted message us ...

"Hey, do you need a see-through background for your

Currently, I am implementing the JS library found at . Unfortunately, I am struggling to make the background transparent or any other color. It appears that the issue lies in the fact that the tab styles are being overridden by the JS library whenever the ...

Updating route from action within Vuex Store

Exploring ways to trigger a route change from the store. I attempted to import router directly into the store and use the following code: LOG_OUT({commit}){ commit('LOG_OUT__MUTATION'); router.push({ name: 'Login' }) } Unfo ...

Having trouble triggering a click event with JQuery

I have a hidden link for downloading Audio Files that I want the user to access using a button. However, I am having trouble triggering the click event. Below is the HTML code: <a class="APopupDown" data-icon="home" id="DownloadFile" href="http://yaho ...

Jquery countdown that persists even after refreshing the page with F5

Currently, I am in search of a jquery plugin for a countdown feature that will retain the timer even if the page is refreshed. I am developing an application for a questionnaire and I would like to display a countdown timer set to 60 minutes. In my applica ...

I am experiencing an issue with the functionality of Handlebars registerPartial()

Check out my code snippet on JsFiddle Error Message: Uncaught Error - The partial social could not be found Note: I have made sure to include all necessary libraries. Looking forward to your assistance. Thank you! ...

Setting up JW Player with a YouTube Embed URL

Embed link Is it possible to embed a YouTube link in my JW Player without disrupting the design? I have a specific design for the JW Player frame that I need to retain while incorporating the YouTube link. I have searched extensively but haven't foun ...