[AngularJS] Angular 1.3 new $q constructor

<!DOCTYPE html>
<html ng-app="app">
<head lang="en">
    <meta charset="UTF-8">
    <title>new $q constructor </title>
    <script src="bower_components/angular/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as vm">
    <button ng-click="vm.fire(true)">Reject it</button>
    <button ng-click="vm.fire(false)">Resolve it</button>
    <h3>Last Resolved Value</h3>
    <pre>{{vm.resolveData | json}}</pre>

    <h3>Last Rejected Value</h3>
    <pre>{{vm.rejectData | json}}</pre>
</body>
</html>

 

/**
 * Created by Answer1215 on 11/13/2014.
 */
function MainCtrl($q){
    'use strict';
    var vm = this;
    vm.fire = fire;
    vm.resolveData = null;
    vm.rejectData = null;

    function fire(rejectIt){
        console.log('fire');
        doAsync(rejectIt).then(function(data){
            vm.resolveData = data;
        }, function(error){
            vm.rejectData = error;
        });
    }

    //$q usually sepreate from the logic
    function doAsync(rejectIt){
        return $q(function(resolve, reject){
            setTimeout(function(){
                var doneTime = +new Date();
                console.log(doneTime);
                if(!rejectIt){
                    resolve({
                        resolveData: 'resolve it at '+doneTime
                    });
                }else{
                    reject({
                        rejectData: 'reject it at '+doneTime
                    });
                }
            }, 500);
        });
    }
}

angular.module('app',[])
.controller('MainCtrl', MainCtrl);

 

Read More: http://jsbin.com/jetoyo/4/edit?html,js,output

posted @ 2014-11-13 22:54  Zhentiw  阅读(374)  评论(0编辑  收藏  举报