Tuesday, June 16, 2015

Angular Js Factory and $q


<!DOCTYPE html>
<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="customersCtrl">

        <ul>
            <li ng-repeat="x in names">
                {{ x.Name + ', ' + x.Country }}
            </li>
        </ul>

    </div>

    <script>
        angular.module('myApp', [])
           .factory('customersService', function ($http, $q) {
               var deferred = $q.defer();

               return {
                   getPerson: function () {
                       return $http.get("/api/Home/getperson")
                           .then(function (response) {
                               // promise is fulfilled
                               deferred.resolve(response);
                               return deferred.promise;
                           }, function (response) {
                                deferred.reject(response);
                              return deferred.promise;
                           })
                       ;
                   }
               }

           })
           .controller("customersCtrl", function ($scope, $q, customersService) {

               customersService.getPerson().then(
                       function (result) {
                           $scope.names = result.data;
                       },
                       function (error) {
                           // handle errors here
                           alert('error');
                       }
                   );
           });

    </script>

</body>
</html>

No comments:

Post a Comment