Invoke AngularJS method using an Ajax request

As a novice in using Angular, I am eager to explore its capabilities, especially in retrieving return values from the controller.

I have been contemplating if it's feasible to make an ajax call and then retrieve the return value to be passed into Angular.

To achieve this, I have created a function that fetches data from my controller using ajax:

function myData() {
    $.ajax({
        url: '/Home/testGetMSSQL',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            return data
        },
        error: function (jqXhr, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });        
}

My objective is to incorporate the above function in my Angular call like so:

var app = angular.module('myApp', ['ui.bootstrap']);
    app.controller('myCtrl', function ($scope) {
        $scope.customers = myData(),
            $scope.people = [],
            $scope.currentPage = 1,
            $scope.numPerPage = 5,
            $scope.maxSize = 5;

        $scope.numPages = function () {
            return Math.ceil($scope.customers.length / $scope.numPerPage);
        };

        $scope.$watch('currentPage + numPerPage', function () {
            var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                , end = begin + $scope.numPerPage;

            $scope.people = $scope.customers.slice(begin, end);
        });

    });

Currently, this approach is not functioning but when I hard code a value, it works perfectly:

var app = angular.module('myApp', ['ui.bootstrap']);
    app.controller('myCtrl', function ($scope) {
        $scope.customers = [{
            "Name": "Alfreds Futterkiste",
            "City": "Berlin",
            "Country": "Germany"
        }],
            $scope.people = [],
            $scope.currentPage = 1,
            $scope.numPerPage = 5,
            $scope.maxSize = 5;

        $scope.numPages = function () {
            return Math.ceil($scope.customers.length / $scope.numPerPage);
        };

        $scope.$watch('currentPage + numPerPage', function () {
            var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                , end = begin + $scope.numPerPage;

            $scope.people = $scope.customers.slice(begin, end);
        });

    });

I found inspiration from this example: https://codepen.io/jyothinagaraj/pen/ALoYgO

Any suggestions or comments are welcome. Thanks in advance!

Answer №1

Consider using $http instead of relying on ajax to ensure it remains within the angular digest cycle


var app = angular.module('myApp', ['ui.bootstrap']);
    app.controller('myCtrl', function ($scope,$http) {
     $scope.spinner = true;
     $scope.init = function(){

        $http.get('/Home/testGetMSSQL').then(function(res){
            $scope.customers = res;
            $scope.spinner = false;
        })
     }
     $scope.people = [],
      $scope.currentPage = 1,
      $scope.numPerPage = 5,
      $scope.maxSize = 5;

      $scope.numPages = function () {
            return Math.ceil($scope.customers.length / $scope.numPerPage);
      };

        $scope.$watch('currentPage + numPerPage', function () {
            var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                , end = begin + $scope.numPerPage;

            $scope.people = $scope.customers.slice(begin, end);
        });

    });

and in html:

<div ng-controller="myCtrl" ng-init="init()" >

Note: Implement a spinner to provide feedback while the UI is disabled until the $scope.customer data is retrieved from the server.

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

"Bringing in" ES6 for Node

I am interested in utilizing import from ES6 instead of require from common.js in Node. Surprisingly, I initially assumed that import would function automatically in Node. However, it appears that it does not. Is there a specific npm package that needs t ...

Assigning a value to a JavaScript variable using Ajax

Struggling with a problem for hours and still can't find the issue... A registration form is set up for users to create accounts. When the submit button is clicked, a validateForm function is triggered. Within this function, some JavaScript tests ar ...

javascript unable to delete cookie

After conducting extensive research across various articles and links on deleting cookies using JavaScript, I have encountered an issue where the JavaScript code does not seem to be functioning as expected. The code I utilized for setting cookie values usi ...

Determining light sources for unique shapes using Three.js

After creating a custom geometry and successfully using geometry.computeFaceNormals() to achieve correct lighting, I encountered an issue when attempting to animate the geometry. Even though I call geometry.computeFaceNormals() within the animation loop, t ...

The error message "Node.js is throwing a next() error that is not a

var express = require('express'); var app = express(); var middleware = { requireAuthentication: function(req, res, next){ console.log("private route hit"); next(); } }; app.use(middleware.requireAuthentication()); app ...

The animation in ThreeJs encounters context issues within Angular 2

I am trying to incorporate ThreeJs into my Angular 2 project. I have successfully rendered a scene with a simple cube, but I ran into an issue when using the animate() function. Here is the code snippet: import { OnInit, Component } from '@angular/co ...

Automatically refresh your web application in Intellij IDEA

Currently, I am in the process of developing a web application using AngularJS and Spring boot with IntelliJ IDEA 15 and Tomcat. One issue that I have encountered is that every time I make changes to my static content, I need to restart the application to ...

metamorphosis array

I have a unique situation where I'm working with an SVG map containing a g element container. Within the g element, there are items with specific x and y positions. My challenge is to create a mouse wheel zoom function that pans the g element in a wa ...

Incorporating a parameter into a <div> only when the parameter holds a value

Being new to web development, I have a rather basic query. If the datainfo prop variable is not empty, I'd like to include a data attribute in the div tag. <div style={{height: props.height - handleHeight()}} data={datainfo ? datainfo : ""}> C ...

Unlocking secure content with Ajax

Trying to access a webservice or webpage solely through ajax, as it is the only allowed method for some reason. The webservice is secured with corporate SSO. When requesting webpage X for the first time, you are redirected to login page Y, outside of the a ...

Is it possible for PHP to return jQuery code and have it execute immediately upon being echoed?

As someone who is new to jQuery and PHP, I have been tasked by my boss to create a login system for a web page that contains sensitive company information. The challenge is that this webpage consists of just one html/php file. Here is what I have done so ...

Leverage the power of PHP array values in your Javascript code

I am facing an issue where I cannot seem to run my javascript functions on a page after retrieving values from a local database using PHP. When the PHP code is included within my javascript, the function does not execute at all. However, if I separate the ...

Is it possible to utilize THREE js ExtrudeGeometry to manipulate a shape along a jagged path?

Is it possible to use CatmullRomCurve3 to extrude over a sharp line, as shown in the image below: https://i.sstatic.net/wJNEv.png I am looking to achieve the following result: https://i.sstatic.net/Fe87K.png The goal is to achieve this with minimal pol ...

Switching picture using dropdown menu in javascript/jquery

Having some trouble trying to recreate this example. The initial image shows up, but it doesn't change when I select a different option. Still getting the hang of javascript so any help is appreciated. <html> <head> <script src="/j ...

Adding an Item to the Cart in React.js

Currently, I am delving into react.js and endeavoring to incorporate a fundamental add to cart feature. My aim is to maintain simplicity in order to grasp the entire process. The setup involves two cards - one showcasing the items and another where the sel ...

Adding and removing attributes with Jquery upon clicking a button

How can I make my listed items add an ID when clicked, or what am I doing incorrectly? $('.ex-menuLi #tt').attr('id', 'test'); $('.ex-menuLi').on('click', function(){ $(this).attr('id', &apos ...

What could be the reason that changing document.body would impact its future accessibility?

This particular block of code functions exactly as anticipated: let vw, vh [vw, vh] = [document.body.clientWidth, document.body.clientHeight] console.log(vw) However, the behavior of this next snippet is not what I expected. It appears that simply havi ...

Using jQuery to handle nested div elements and triggering a click event only once when the inner div is clicked

I have a situation where I have nested divs. When the inner div (closeme) is clicked, I do not want the click event of the outer div (container) to be triggered. How can I achieve this? html <div id="container"> content <div id="closeme">< ...

Turning off ArrowUp and ArrowDown in React

Is there a way to prevent the ArrowUp and ArrowDown keys from changing the input value in an input field using React? How can I achieve this? So far, my attempted solution has been: function onKeyPressRegex(e) { if (!/[0-9]/.test(e.key) || e.key === &ap ...

"Interactive demonstration" image toggle through file upload

I have a project to create a "demo" website for a client who wants to showcase the template to their clients. A key feature they are interested in is allowing users to upload their logo (in jpg or png format) and see it replace the default logo image insta ...