angularjs中如何在异步请求执行完以后再执行其他函数?

angularjs中如何在异步请求执行完以后再执行其他函数?

之前脑袋回路就是从上到下的执行js,直到有一次我的页面上已经显示了空才走到angularjs里的$http的成功回调函数里,然后才开始正视工程里异步请求对项目的影响。

第一反应是放回调就可以了:

var app = angular.module('myApp', []);
	
app.controller('testCtrl', function($scope, $http) {
	$http({
		method: 'GET',
		url: 'xxx'
	}).then(function succ(data) {
			$scope.testSucc();
		}, function err(data) {
			$scope.testErr();
			
	});
  	$scope.testSucc = function(){
		console.log("success func");
	}
	$scope.testErr = function(){
		console.log("error func");
	}
});

但是如果其他函数($scope.testSucc、$scope.testErr())不是这个控制器里的呢?对,你可以使用广播事件,然后在其子控制器里监听这个回调结果,但是我不喜欢这种方法,因为一个函数还好,如果是整个页面都依赖这个这个结果,不会累死啊。

我使用了一个小技巧:angularjs的控制器执行是在页面加载这个控制器所对应的页面的时候才会执行,所以在异步请求前设置页面不加载,异步请求成功的函数里设置页面加载就可以了。这里就利用了ng-if的特点了:ng-if 在后面表达式为 true 的时候才创建这个 dom 节点。

html页面如下:

<body>
<div ng-app="myApp" ng-controller="fatherCtrl">
    <div ng-if="succResult" ng-controller="childrenCtrl">
        <p>{{data}}</p>
    </div>
</div>
</body>

js:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.succResult = false;
    $http({
        method: 'GET',
        url: 'xxx'
    }).then(function succ(data) {
            $scope.succResult = true;
            $scope.data=data;
        }, function err(data) {
            $scope.testErr();    
    });
});

以上是我利用ng-if和$http实现异步回调的效果。

原文地址:https://www.cnblogs.com/mini-fan/p/7508703.html