Angular controller function failing to assign data to $scope variable

Can someone please help me out with this issue? I need to display different types of bills for various tables in my view, and here's what I came up with. But I have a feeling it might not be the best approach.

In my view, I am calling:

Table 1:

{{billsTypeVariableIncome}}

Table 2:

{{billsTypeVariableBills}}

This is how I've set up my controller:

$scope.billsTypeVariableIncome = getBillsByType(1);
$scope.billsTypeVariableBills = getBillsByType(2);

function getBillsByType(bill_type){

        $http.get("/api/bills/by/type/"+bill_type).
        success(function(data){
           return data;

        }).
        error(function(data){

            console.log('Error ' + data);

        })
    }

I'm new at this, so there's a good chance I'm on the wrong track. Any advice or guidance would be greatly appreciated!

Answer №1

When utilizing the $http service, it will consistently return a promise due to the asynchronous nature of AJAX requests and the uncertainty of when the request will be completed. Promises are used for handling callbacks in such scenarios.

If you anticipate receiving data from a promise object directly, that is not possible. Therefore, it is recommended to modify your code as shown below:

$scope.getBillsByType = function(billType, variableName) {
    $http.get("/api/bills/by/type/" + billType).
    success(function(data) {
       $scope[variableName] = data;
    }).
    error(function(data){
        console.log('Error ' + data);
    })
};

$scope.getBillsByType(1, 'billsTypeVariableIncome');
$scope.getBillsByType(2, 'billsTypeVariableBills');

This serves as a basic example, but there are alternative approaches you can explore.

I hope this information proves useful!

Warm regards,
SA

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

Is there a way to specify both a fixed width and a custom resizable length for a Spring <form:textarea /> element?

Despite extensive research, I have yet to find an answer to my specific problem. Within a model window, I have a textarea element: <div class="form-group"> <label for="groupDescription" class="col-sm-2 control-label"> Descripti ...

Sending Location Data From JavaScript to PHP via Cookies

I encountered an issue while attempting to send Geolocation coordinates from JavaScript to PHP using Cookies. The error message I am receiving is: Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/samepage.php on line 24 The file name ...

Is Three.js capable of creating procedurally-generated bump or specular maps?

Using Three.js, it is common practice to utilize external images for bump maps and specular maps: var specular = THREE.ImageUtils.loadTexture("path/to/file.png"); var myMaterial = new THREE.MeshPhongMaterial(); myMaterial.specularMap = specular; However, ...

The function of sending files quickly

Currently, I am working on developing an API with node.js. In this project, I have a PDF file saved in the Temp folder, and my goal is to send it using res.sendFile(). However, every time I attempt to do so, it sends back an empty file instead of the PDF f ...

Unable to cancel the RTK query request

It's quite a dilemma. I need to handle the request differently when there is no user present. I've attempted different approaches like this and that const { data: carts = [] as ICart[], isFetching } = api.useGetCartProductsQuery(user.id, { skip: ...

What could be causing the slow compilation of my Next.js pages within the app directory, and what steps can be taken to improve the speed of this

Currently, I am working on a Next.js project that uses the 'app' directory structure. However, during local development, I have been facing significant delays in compile times. Here's a breakdown of the compile times I am encountering: - Th ...

The ng-model attribute in AngularJS is failing to properly set the selected="selected" attribute within the select element

Having an issue with displaying the current value in the <select> tags on my AngularJS page for editing surgeries. While all other form fields show their current values, the <select> tags are not cooperating. I have set up a factory with ngRes ...

Leverage the power of JavaScript strings within PHP

In my JavaScript code, I have a string variable. <script type="text/javascript"> Var string='String to use'; </script> Now I need to retrieve the text from the string variable in PHP. What is the best way to access or utilize it? ...

Notification system for managing recurring tasks

Situation I am currently working on an application where users are assigned daily tasks such as "wash the window, clean the floor," and so on. Each task has a specific recurrence interval and must be completed at least once within that time frame. For e ...

dont forget to preserve the checkbox and radio button selections when the page is refreshed

I have developed a filter using jQuery and Laravel (PHP) to filter data based on checkbox or radio button selections. However, after refreshing the page, the checked state of the checkboxes or radio buttons is lost. I need the checked state to persist even ...

Issue with facebook button in reactJS where onClick() event is not being triggered

I'm facing an issue where my onClick handler is not working with the Facebook button from https://developers.facebook.com/docs/facebook-login/web/login-button/. However, it works fine with a regular div element. Any thoughts on why the onClick event ...

Experiencing trouble with data visualization through Ajax in the Data src Datatable

I am facing an issue with my datatable as it is not displaying the data that has been fetched from API URLs and processed into an array called return_data. Here is the code snippet: $(document).ready(function() { $('#datatable2').DataTabl ...

Drop-down menu offering multiple selections

I have a code where I want to enable multiple selection with both dropdown and checkboxes. However, when I use the multiple attribute in the select tag, it generates a list-type view which is not what I desire. Can someone please help me achieve the desire ...

I am wondering about the proper method for deleting multiple records simultaneously in Ember Data

My current challenge involves managing a list of record IDs, such as [1, 20, 20]. The process of individually querying and deleting each item is proving to be quite inefficient. store.findRecord('post', 1).then(function(post) { post.deleteRec ...

Creating a dynamic category menu using angularJS

I'm struggling with the logic behind creating a category menu using AngularJS I need to display all categories with a parent category id of 0. Once that is done, I want to display all subcategories that belong to each parent category. The final categ ...

Move the cursor to a specific position within a contentEditable <div> element

I am in search of a reliable solution that works seamlessly across browsers to set the cursor/caret position to the last known location when a contentEditable='on' <div> regains focus. By default, the cursor/caret in a content editable div ...

Error in Winston: Unable to determine the length of undefined property

I encountered an issue with my Winston Transport in the express backend of my MERN app. The error message reads: error: uncaughtException: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefi ...

"Maximizing Efficiency: Chaining Several Actions Using the JavaScript Ternary Operator

When the condition is true, how can I chain two operations together? a = 96 c = 0 a > 50 ? c += 1 && console.log('passed') : console.log('try more') I attempted chaining with && and it successfully worked in react, b ...

The HTML elements in my JSX code seem to constantly shift around whenever I resize my webpage

Using react.js, I'm currently developing a website that appears like this before resizing: pre-resize_screenshot_website However, upon vertical or diagonal resizing, the layout becomes distorted especially in the 'availability search bar' ...

Is there a way to display the output of jQuery in an input box rather than a span?

I need to display the result of this function in an input box instead of a span tag because I plan to utilize the result in the following form. function checkChange(){ $.ajax({ url: "ordercalculate.php", data: $('form').seria ...