Angular js Button click

356 Views Asked by At

I have created a button which on click gives an ajax call and the server response obtained through ajax is binded to table using angular js. The issue is according to me on first click of the button itself the data must appear on the webpage.But this happens on second click of the button.I am able to sort and filter data properly but the problem is i need to click button two times separately before it fetches the table

<script>
    var fooddata = angular.module("fooddata", []);
        fooddata.controller("myCtrl", function ($scope) {
            $scope.binddata = function () {
                $.ajax({
                    type: "POST",
                    url: "ASSIGN.aspx/OnDataFetch",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        response.d = $.parseJSON(response.d);
                        $scope.foods = response;
                    },
                    failure: function (response) {
                        alert(response.d);
                    },
                    error: function (response) {
                        alert(response.d);
                    }
                });
            }
        }
    );   
</script>

<body> 
    <div id="id001"></div>
    <div ng-app="fooddata" ng-controller="myCtrl">

    // enter code here

       <button ng-click="binddata()">Data Fetch</button>
       <div>Sort by: 
            <select ng-model="sortExpression">
                <option value="food_id">Food id</option>
                <option value="type">Type</option>
                <option value="priority">Priority</option>
            </select>
       </div>
       Filter By Any:
       <div><input type="text" ng-model="search" /></div>
       <table border="1" cellpadding="10">
          <tr><td>Food id</td><td>Type</td><td>priority</td></tr>
          <tr ng-repeat="items in foods.d  | orderBy:sortExpression | filter:search">
          <!-- <td ng-repeat="cell in items">{{cell}}</td>  -->
            <td>{{items.food_id}}</td> 
            <td>{{items.type}}</td>  
            <td>{{items.priority}}</td>  
          </tr>
      </table>
   </div>
</body>
3

There are 3 best solutions below

0
On

You problem is, you are using $.ajax. which won't running digest cycle resultant the binding will not update on html/scope. You must use $http instead of $.ajax, If you use $http angular will run digest cycle when the ajax completed.

Code

$http({ //<-- make sure you have added $http dependency on controller
    method: "POST",
    url: "ASSIGN.aspx/OnDataFetch",
    headers: {
        'Content-Type': "application/json; charset=utf-8"
    }

}).
success(function(response) {
    response.d = $.parseJSON(response.d);
    $scope.foods = response;
}).
error(function(response) {
    alert(response.d);
})

Use jQuery ajax while angular provided you $http is problematic and considered as bad practice.

0
On

Define you controller like this:

fooddata.controller("myCtrl", function ($scope, $http) {

And then do this do run ajax

$scope.binddata = function(){
    var request = $http({
                        method: "post",
                        url: "yourAjaxFile.php",
                        data: {
                            //data
                        },
                        //contentType,
                        headers: {
                            'Content-Type': "application/json; charset=utf-8"
                        }
                    });

                    /* Check whether the HTTP Request is successful or not. */
                    request.success(function (data) {

                        $scope.foods = data;
                    });
}
0
On

In case of Async calls like $.ajax(), the angular scope is no longer updated on inside events. So you need to do $apply manually to apply the updates or you can go forward with any of the other solutions provided by others.
They too work well.

<html><head><script>
   var fooddata = angular.module("fooddata", []);
            fooddata.controller("myCtrl", function ($scope) {
                $scope.binddata = function () {
                    $.ajax({
                        type: "POST",
                        url: "ASSIGN.aspx/OnDataFetch",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            response.d = $.parseJSON(response.d);
                            $scope.foods = response;
                            if(!$scope.$$phase)
                                  $scope.$apply();
                                                },
                        failure: function (response) {
                            alert(response.d);
                        },
                        error: function (response) {
                            alert(response.d);
                        }
                    });
                }
            }
              );

      </script>
    <body>
        <div id="id001"></div>
      <div ng-app="fooddata" ng-controller="myCtrl">


        enter code here

       <button ng-click="binddata()">Data Fetch</button>
     <div>Sort by: 
                <select ng-model="sortExpression">
                        <option value="food_id">Food id</option>
                        <option value="type">Type</option>
                        <option value="priority">Priority</option>
                    </select>
              </div>  Filter By Any:
                        <div><input type="text" ng-model="search" /></div>
    <table border="1" cellpadding="10">
    <tr><td>Food id</td><td>Type</td><td>priority</td></tr>
    <tr ng-repeat="items in foods.d  | orderBy:sortExpression | filter:search">
       <!-- <td ng-repeat="cell in items">{{cell}}</td>  -->
        <td>{{items.food_id}}</td> 
        <td>{{items.type}}</td>  
         <td>{{items.priority}}</td>  
    </tr>
    </table>
    </div>
        </body>
</html>