Search code examples
javascriptjqueryangularjswebmethod

How to maintain binding when input button is clicked using webmethod in angular


I am trying to update my angular model using a known working webmethod (.net).

  • I get data back from my webmethod logged to the console successfully.

  • It updates the input-box value as well.

  • But this doesn't update my angular model binding.

What am I doing wrong?

HTML

 <input class="btn-primary" />
 <input class="txtCalls" ng-model="TotalCalls"/>

Angular

$scope.TotalCalls;

CodeBehind

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public static string GetCallData()
    {
         String Calls = "34";
         return Calls;
    }

Ajax Call

$(document).ready(function () {
            $('.btn-primary').click(function () {
                $.ajax({
                    type: "GET",
                    url: "Stats.aspx/GetCallData",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        $('.txtCalls').text(response.d);
                        console.log(response.d);
                    },

                    failure: function (response) {
                        alert(response.d);
                        console.log(response.d);
                    }
                });
             });

Solution

  • it is because this is an JQUERY/Ajax call not an angular call. You need to make the call from a angular-controller and use $http.get instead of $.ajax

    your button .btn-primary should add an ng-click="someMethod()" instead of the JQuery on('click'). Like:

    <input class="btn-primary" ng-click="someMethod() />
    

    I would assume you already have a controller so in it you will need to implement someMethod like:

    $scope.someMethod = function(){  $http.get(...) };  
    

    Additionally angular is an MVVM framework and as part of this pattern you update the Model(data) instead of the view html>form>input control the two way binding will do the rest for you.