Tuesday, July 2, 2013

AngularJS - How to add a JavaScript method for calling by ng-click and serializing your object with JSON filter

Sometimes you may have trouble figuring out how to add a method that can be called by a ng-click directive. Here is my sample code with AngularJS that will be called by ng-click. Also this code uses json filter to convert my object to a string representation of my data. There is a few points to be considered:

1: You need to put the method in scope of your controller. So it can be seen by the controller.

2: You need to add $filter to the parameters of your controller. Thus AngularJS will inject filter object to be accessible in all methods you add to your controller scope.

Here is the JavaScript code:

function MyJsCtrl($scope, $filter)
{
    $scope.submitData = function () {

       $scope.Message = 'Sending...';
       $scope.DisableSendButton = true;
       var json = $filter('json')($scope.data);
       Send(json);

    };
       …

}

And this is the HTML tags:
<input type="button" ng-click="submitData()" value="Submit" ng-disabled="DisableSendButton"/> {{Message}}



I hope this short sample help you figure out your event handler.

No comments:

Post a Comment