angularjs中使用$q.defer

魔豆發表於2016-09-13

方法method1和方法method2的區別,我還正在研究中。。。待新增

程式碼如下:

<html ng-app="myApp">
<head>
<title>angularjs-ajax</title>
<script type="text/javascript" src="angular.min.js" charset="utf-8"></script>
</head>
<body ng-controller="ctrl">
<input type="button" value="抓取頁面內容1" ng-click="method1()" /> 
<input type="button" value="抓取頁面內容2" ng-click="method2()" /> 
<div style="border: 1px solid #ccc;width: 500px;height:400px;">{{content}}</div>
<script>
    var app = angular.module('myApp',[]);
    app.controller("ctrl",function($scope,$http,$q){
        
        $scope.method1 = function() {
            $http.get('a1.htm').success(function (data) {
                $scope.content = data;
            });
        };
        
        $scope.method2 = function() {
            var deferred = $q.defer();
            $http.get("a1.htm").success(function (data) {
                $scope.content = data;
                deferred.resolve(response);
            }).error(function(error){
                alert(123);
                deferred.reject(error);
            });
        };
    });
    </script>    
</body>
</html>

 

相關文章