angularjs - $http post in Angular.js -
i've started learning angular.js. how re-write following code in angular.js?
var postdata = "<requestinfo> " + "<event>getpersons</event> " + "</requestinfo>"; var req = new xmlhttprequest(); req.onreadystatechange = function () { if (req.readystate == 4 || req.readystate == "complete") { if (req.status == 200) { console.log(req.responsetext); } } }; try { req.open('post', 'http://samedomain.com/getpersons', false); req.send(postdata); } catch (e) { console.log(e); }
here's have far -
function testcontroller($scope) { $scope.persons = $http({ url: 'http://samedomain.com/getpersons', method: "post", data: postdata, headers: {'content-type': 'application/x-www-form-urlencoded'} }).success(function (data, status, headers, config) { $scope.data = data; // how pass $scope.persons? }).error(function (data, status, headers, config) { $scope.status = status; }); }
html
<div ng-controller="testcontroller"> <li ng-repeat="person in persons">{{person.name}}</li> </div>
am in right direction?
in current function if assigning $scope.persons
$http
promise object $http
returns promise object.
so instead of assigning scope.persons
$http should assign $scope.persons
inside success of $http
mentioned below:
function testcontroller($scope, $http) { $http({ url: 'http://samedomain.com/getpersons', method: "post", data: postdata, headers: {'content-type': 'application/x-www-form-urlencoded'} }).success(function (data, status, headers, config) { $scope.persons = data; // assign $scope.persons here promise resolved here }).error(function (data, status, headers, config) { $scope.status = status; }); }
Comments
Post a Comment