javascript - 与 Angular 同步事件(如线程 'join()' 函数)

标签 javascript angularjs

我寻找一些简单的东西,例如用于线程但用于 Angular join()

在我的 Controller 中:

vehiclesService.getVehicles().then(function(sth){
    $scope.vehicles = sth.data;
    $scope.isend();//this call suck in my mind
});
vehiclesService.getFitment().then(function(sth){
    $scope.fitment = sth.data;
    $scope.isend();//this call suck in my mind
});
vehiclesService.getTagsList().then(function(sth){
    $scope.tags = sth.data;
    $scope.isend();//this call suck in my mind
});

我想要在所有 3 个变量都初始化时调用函数。目前的工作。但我心里却很难过。我也试试

$scope.$watch('vehicles', function() {
   $scope.isend();
});

$scope.$watch('fitment', function() {
   $scope.isend();
});

$scope.$watch('tags', function() {
   $scope.isend();
});

$scope.isend = function(){
    if($scope.vehicles !== undefined && $scope.fitment !== undefined && $scope.tags !== undefined)
        alert('doSomething');
}

它可以工作,但我发现它更糟糕!

在 Angular 中这样做的好方法是什么?

最佳答案

使用$q.all - 当所有的 promise 都得到解决时,返回的 promise 也得到解决。

$q.all([
    vehiclesService.getVehicles(),
    vehiclesService.getFitment(),
    vehiclesService.getTagsList()
]).then(function(results) {
   // results is an array
   $scope.isend();
});

关于javascript - 与 Angular 同步事件(如线程 'join()' 函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31537122/

相关文章:

javascript - 我的大部分 Bootstrap 3.1.1 样式都没有应用

javascript - Nightwatch 获取 api 结果以填充变量然后运行使用该变量的测试的正确方法

javascript - Angularjs 在创建 dom 元素时的性能,纯 js 与 jqlite

angularjs http拦截器类(ES6)失去与 'this'的绑定(bind)

javascript - 动态生成带换行符的span标签

javascript - 减少 IE8 上的 mixin 生成错误

javascript - 限制 var 乘法总数中的位数

javascript - 在javascript中的类定义中添加原型(prototype)

javascript - Angularjs Binding 2指令范围模型到父 Controller 模型

javascript - 如何使用 AngularJS 检索外部网站的内容(逐个元素)