Angular http POST sample

We’ll start with the html code of our httpPost.html page.

<h1>{{pageName}}</h1>
 
 Add rule: <input type="text" ng-model="newRule" />
<a href="#" class="btn btn-default" ng-click="addRule()">Add</a>
<hr>
<ul> 
    <li  ng-repeat="rule in rules">
        {{rule}}
    </li>
</ul>
 

Our controller is that pulls the data from an API using $http.get to get existing rules and $http.post to save a new rule and reload the $scope.rules:


///we need to inject the $http service 
myApp.controller('httpPostController',['$scope', '$http', function($scope, $http){
    
    $scope.pageName = 'httpPost';
    
    //get existing rules from the api's index (GET) action
    $http.get('/api')
     .success(function(result){
         $scope.rules = result; //it returns a json list of rules 
     })
     .error(function(data,status){
         console.log(data);
     }) 
    
     $scope.newRule = '';  //declare a rule field to be used by textbox to enter new rule
     $scope.addRule = function()
     {
         $http.post('/api',{newRule: $scope.newRule}) //json to pass to api is the 2nd param
         .success(function (result){
             $scope.rules = result; // this api is returning all existing when we add a rule
             $scope.newRule = '';   //clear out the variable
         })
         .error(function(data, status){
             console.log(data);
         });
         
     };
     
}]);     

NOTE: this code was not tested so possible typo’s.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s