Load the dropdown menu in the select element using the AngularJS $ngresource promise

I have a select box on my webpage that I need to fill with data received from a server. I am currently using a service to fetch this data, but I'm unsure how to access the values returned from the promise and populate the ng-options in the select tag.

Fetching data from the resource:

  $scope.categories = Category.all({sorting:"asc"});

Resource configuration:

factory('Category', function ($resource) {
    return $resource('api/categories/:id', {}, {
        all: {method: "GET", isArray: true, params: {sorting: '@sorting'}},
        update: {
            method: "PUT",
            params: {
                id: "@id"
            }
        }
    })
}).

Answer №1

When you make a call to Category.all(), an array will be returned that gets filled with the retrieved values once the http request is complete. If you need to execute some code after the request finishes, you can do so by passing a callback function like this:

$scope.categories = Category.all({sorting:"asc"}, function() {
    // perform actions on $scope.categories here
});

Alternatively, you can also work with a promise in the following way:

$scope.categories = Category.all({sorting:"asc"})
    .$promise.then(function(categories) {
        // handle the categories data here
    });

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

Unable to locate element using Protractor

I'm struggling with getting protractor to work correctly when testing my angular app. The code in my spec file is as follows: describe('app login', function() { it('should allow admin user to log in', function() { browse ...

Axios transforms into a vow

The console.log outputs of the api and axios variables in the provided code are showing different results, with the state axios becoming a Promise even though no changes were made. The 'api' variable holds the normal axios instance while 'ax ...

What is the most effective method for developing real-time applications with Angular.js and Node.js?

I am new to Angular.js and Node.js, and I've discovered two methods for creating real-time applications. The first involves using Socket.io, while the second utilizes RESTful with setInterval() function as a client-side solution. I experimented with b ...

Utilize the directive method within the transcluded content by making a call

Trying to call a method within a directive from transcluded content. The structure of my HTML is: <typeahead class="typeahead" model="customers" filtered-model="customersfiltered" ng-model="selectedcustomer"> <ul> <li ng-click="select ...

Exploring the importance of defining a JSONP callback function

I am relatively new to JavaScript and struggling with an issue in my code. My code includes an Ajax request to a server, and I receive a response from it. Due to the cross-domain nature of the request, I am utilizing JSONP. $.ajax({ url: "***", c ...

Encountering a 400 bad request error when attempting to utilize AJAX within a WordPress environment

I am encountering a 400 error while attempting to retrieve the response from WordPress AJAX. Despite multiple attempts, I have been unable to pinpoint the root cause of the issue. The jQuery version being used is 3.6 and the filter.js file appears to be fu ...

Trouble with loading scripts after transitioning to a new page with AJAX (Barba.js)

Exploring the potential of using AJAX for smooth page transitions. Tried two different methods so far: manually coded transition from () and Barba.js approach (). With both methods, scripts work on initial load but fail to execute when navigating to anot ...

Updating parameters in Node.js with mongoose

script.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var scriptSchema = new Schema({ status: {type: String, default: 'INCOMPLETE'}, code: String, createdDate: {type: Date, default: Date.now}, user: {t ...

The concept of dynamic schema in Mongoose allows for flexibility and

Currently, I am working on creating a product schema that involves setting pricing in different currencies. However, I am facing confusion regarding how to dynamically create currency options. The pricing may vary in one currency or multiple currencies as ...

JavaScript and .NET Core: Implementing file uploads without the use of FormData or FromFrom

Currently attempting to create a "basic" file upload feature. Utilizing JavaScript on the frontend and .NET Core on the backend. Previously, I had successfully implemented FormData / multipart, FromForm, and iFormFile. However, I have been advised agains ...

What are the differences between Angular's dynamic templating using compile and template function?

I am familiar with the purpose of each item in: compile vs link(pre/post) vs controller Now, consider this simple code: HTML <body ng-controller="mainController"> {{ message }} <div otc-dynamic=""></div> </body> Cont ...

Capture any clicks that fall outside of the specified set

I am facing an issue with my navigation drop down menu. Currently, the pure CSS functionality requires users to click the link again to close the sub-menu. What I want is for the sub-menu to close whenever a click occurs outside of it. I attempted a solu ...

The process of using Jest to test whether a React component correctly renders a list

I've been diving into the world of unit testing and recently developed a small React application that showcases a list of Pokemon. My goal is to create a unit test that verifies if the list renders correctly. However, when I generate a snapshot, it on ...

Using a loop to format the <ol> tag

After creating an HTML script using angular, I was able to successfully display the names in an array as shown below. <div ng-repeat="namep in names"> <li>Name : <span ng-bind="namep.name"></span></li> <li>Age : ...

Modifying specific attributes of an object within the $scope: A step-by-step guide

When working with Angular, if you have code in the view that looks like this: <span ng-model="foo.bar1"></span> <span ng-model="foo.bar2"></span> <span ng-model="foo.bar3"></span> Due to how Angular maps objects, you c ...

Using jQuery to adjust the input value up and down with buttons

var number = 1; $("#counter input").attr('value', number); $("#increase").click(function(){ $("#counter input").attr('value', number++); }); $("#decrease").click(function(){ $("#counter input").attr('value', number--); }); ...

Numerous column pictures that occupy the entire browser screen

I am looking to create a grid of clickable images that expand to cover the width of the browser window without any space on either side. Ideally, I would like each image to be 180x180px in size, but if it's easier they can resize based on the browser ...

Utilizing AJAX to seamlessly transfer id elements to a database

I have the following working code: <script> function displayUserData(str) { if (str=="") { document.getElementById("userDetails").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLH ...

Can a Jquery *compiler* be developed?

Upon encountering this informative question, the idea of creating a jQuery compiler crossed my mind. The concept was to design a tool that could translate jQuery code into raw JavaScript code for execution. In my imagination, the process of executing a bl ...

Sequelize: When attempting to use .get({plain: true})) method, an error is returned indicating that .get is

I'm facing a strange issue as I am able to retrieve only the values of an instance in other parts of my code without any problems. Can you spot what might be wrong with my current code? app.get('/profile', checkAuth, function(req, res) { ...