2017-02-19 91 views
0

我有2個函數bindclub()和displayevent()。我想向bindclub()來運行第一always.I也試圖把兩者的功能在NG-初始化,但它也不能保證運行bindclub()第一如何確保2個函數中的一個先運行

angular.module('app', []).controller("EventCtrl",EventController); 
EventController.$inject = ["$scope", "$http", "$window"]; 

function EventController($scope, $http, $window) { 
    $scope.bindclub = function() { 
      $http({ 
       url: '/Master/bindclub', 
       method: 'post', 

      }).then(function (response) { 
       debugger 
       $scope.clubidname = response.data; 
      }, function() { alert("Error in binding club"); }); 
     } 


     $scope.displayevent = function() { 
      $http({ 
       url: '/Master/displayevent', 
       method: 'post', 

      }).then(function (response) { 
       alert('Displayed'); 

      }, function() { alert('Error in display event'); }); 

     } 
    $scope.bindclub(); 
    $scope.displayevent(); 
} 
+1

可能重複的[如何在JavaScript中觸發事件?](http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript) – ultrajohn

回答

0

使用回調函數等到bindclub函數執行,然後開始displayevent功能

angular.module('app', []).controller("EventCtrl", EventController); 
    EventController.$inject = ["$scope", "$http", "$window"]; 

    function EventController($scope, $http, $window) { 
     $scope.bindclub = function(callback) { 
      $http({ 
       url: '/Master/bindclub', 
       method: 'post', 
      }).then(function(response) { 
       debugger 
       $scope.clubidname = response.data; 
       callback() // callback function 
      }, function() { 
       alert("Error in binding club"); 
       callback()// callback function 
      }); 
     } 
     $scope.displayevent = function() { 
      $http({ 
       url: '/Master/displayevent', 
       method: 'post', 
      }).then(function(response) { 
       alert('Displayed'); 
      }, function() { 
       alert('Error in display event'); 
      }); 
     } 
     $scope.bindclub(function() { 
      $scope.displayevent(); // this execute after bindclub fucntion 
     }); 
    } 
1

是第二個事件依賴第一個事件?如果是,則可以將其設置爲第一個事件的回調事件,以確保它在第一個事件成功時觸發。

0

函數bindclub確實在displayevent之前運行。但是這兩個函數本身使得http調用具有回調。無法保證以您想要的順序執行回調。

我看到的唯一工作是在bindclub中調用回調函數內的其他函數。

另一種方式是讓你連鎖回調。

0

您可以將displayEvent附加到在bindEvent回調中觸發的自定義事件。

看看這個SO後,例如如何做到這一點。

0

回報的承諾,然後把它們連:

$scope.bindclub = function() { 
    //vvvv RETURN httpPromise   
    return $http({ 
     url: '/Master/bindclub', 
     method: 'post', 

    }).then(function (response) { 
     debugger 
     $scope.clubidname = response.data; 
    }, function() { alert("Error in binding club"); }); 
} 

//CHAIN them 
$scope.bindclub() 
    .then(function() { 
     $scope.displayevent(); 
}); 

由於$ HTTP服務返回一個承諾,第二操作可以從第一次操作與第一次承諾的方法鏈接。

相關問題