2

I'm building an ASP.NET MVC application with an Angular front-end. I. Successfully call the Angular GetData() function on page load and I've traced to confirm that Home/DataRefresh is returning data in the correct format.

However when I use data to populate a table in the view nothings shows up, no errors, the calls all complete, the table is just empty.

I have a suspicion that it has something to do with how you have to access the Angular $scope within a non-angular function but I'm too new to angularjs to know for sure. I've read through all the documentation I could find to no avail.

EDIT: Per suggestion here's the $http call and the Angular it's contained in.

app.controller("processModel", function ($scope) {
    $scope.sortType = 'SchedWk';
    $scope.sortReverse = false;

    $scope.GetData = function() {
        $scope.LoadData();
    };

    $scope.LoadData = function() {
        //$.ajax({
        //    type: "GET",
        //    url: 'Home/DataRefresh',
        //    dataType: "json",
        //    success: function (data) {
        //      $scope.data = data;
        //    }, 
        //    error: function (a, b, c) {
        //        alert("The jqXHR object:  " + a + " Error Type:  " + b + " Error Description:  " + c);
        //    }
        //});
        $http({
            method: "GET",
            url: '/Home/DataRefresh'
        }).then(function success(data) {
            $scope.data = data;
        }, function error(errResponse) {
            alert("y u break it tho");
        });
    };  
});
2
  • Were you able to get it working? Commented May 5, 2018 at 21:48
  • Swapping from $.ajax to $http and accessing the data via response.data was the solution. Commented May 5, 2018 at 22:37

4 Answers 4

2

Unlike jQuery AJAX, the $http service returns a response object, of which data is attached as a property of that object:

$http({
    method: "GET",
    url: '/Home/DataRefresh'
}).then(function success( ̶d̶a̶t̶a̶ response) {
    ̶$̶s̶c̶o̶p̶e̶.̶d̶a̶t̶a̶ ̶=̶ ̶d̶a̶t̶a̶;̶
    $scope.data = response.data;
}, function error(errResponse) {
    alert("y u break it tho");
});

From the Docs:

$http Returns

A Promise that will be resolved (request success) or rejected (request failure) with a response object.

The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions.
  • status{number} – HTTP status code of the response.
  • headers{function([headerName])} – Header getter function.
  • config{Object} – The configuration object that was used to generate the request.
  • statusText{string} – HTTP status text of the response.
  • xhrStatus{string} – Status of the XMLHttpRequest (complete, error, timeout or abort).

-— AngularJS $http Service API Reference - Returns.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand how this answers the question. Even in its current state the "data" will still bind to the $scope, but will just be nested down one level like this {"data": [actual response data]}. He was reporting that there was nothing bound to his $scope at all.
@dkaramazov that was because I was using $.ajax before and it wasn't saving to scope at all and so data was just empty. This answer, plus the swap from $.ajax to $http fixed the problem
1

You probably need to call $scope.apply() in the handler after setting the data only the scope because that handler after the ajax call is happening outside of Angular. If you used Angular's $http service instead of $.ajax, you wouldn't need to handle that manually.

4 Comments

Are there any benefits to using AJAX over Angular's built in method or vice versa? Also where would I need to place the call to $scope.apply() right after I assign data to $scope.data or after the ajax call?
In general, you should stick with using Angular's built in capabilities rather than rely on other libraries like jQuery. This issue is a good example why.
I've updated the OP to show the $http code I'm currently trying. DataRefresh wasn't getting hit at all anymore and then I noticed I was getting a Java Runtime error " '$http' is undefined ". Do I need to install a separate package or something to get access to that function?
You need to inject it into your controller
1

You need to inject the $http service first:

app.controller("processModel", function($scope, $http) { 
    $scope.sortType = 'SchedWk'; 
    $scope.sortReverse = false; 
    $scope.GetData = function() { 
        $scope.LoadData(); 
    }; 
    $scope.LoadData = function() { 
       $http({ 
            method: "GET", 
            url: '/HomeDataRefresh' 
       }).then(function success(data) { 
            $scope.data = data; 
       }, function error(errResponse) { 
            alert("y u break it tho");
       }); 
    };
});

Comments

0

You lost the reference to $scope in your AJAX call because it is nested into several JavaScript Functions. When using a JQuery AJAX call you can force AngularJS to pick it up by calling $scope.$apply() which will run the digest loop again.

You really should be using $http or $q to take advantage of Promises in JavaScript. They are very powerful and simplify the use of asynchronous operations in JavaScript.

This link should get you up and running quickly:

https://docs.angularjs.org/api/ng/service/$http

To include $http in your controller you'll need to inject it as in my example.

var app = angular.module('app', []);

app.controller('postController', ['$scope', '$http', function($scope, $http){
    $scope.data = 'empty';
    $scope.runAJAX = function(){
  $http.get('https://jsonplaceholder.typicode.com/posts').then(function(response){
            $scope.data = response.data;
        }).catch(function(error){
            console.log(error);
        });
    }
}]);
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body ng-controller="postController">
    <div>
        {{data}}
    </div>
    <div>
        <input type="button" value="run AJAX" ng-click="runAJAX()"/>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

5 Comments

My answer was in reference to the original state of the question which just had an AJAX call, no $http. Was my explanation of the AJAX call wrong?
No. Unfortunate that OP changed code in the question
What should I do with my answer? I don't want to get down voted again.
Maye just add a mention about "when using using $.ajax" since it is outside angular context
Done. I appreciate you clarifying that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.