2017-02-19 7 views
0

bindclub()とdisplayevent()の2つの関数があります。 2つ目のイベントに依存している私も、NG-のinitの両方の機能を入れしようとした最初のalways.Iを実行するbindclub()を確保したいが、それはまた2つの関数のうち1つが最初に実行されるようにする方法

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

最初bindclub()を実行することを保証しません。最初のイベント? yesの場合、最初のイベントのコールバックイベントとして設定して、最初のイベントの成功時に確実にトリガーされるようにすることができます。

0

関数bindclubは、実際に表示される前に実行されています。しかし、これらの2つの関数自体は、コールバックを持つhttp呼び出しを行います。あなたが望む順序でコールバックを実行させる保証はありません。

私が見ている唯一の問題は、bindclubのコールバックの中で他の関数を呼び出すことです。

もう1つの方法は、コールバックをチェーンすることです。

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サービスは約束を返すので、第二の最初の約束の.thenメソッドによる最初の操作から操作を連鎖させることができます。

関連する問題