2015-08-13 20 views
0

我試圖彈出父控制器上的模式和使用後做一些孩子點擊一個按鈕如何在我的情況來檢測單擊事件

例如, 子控制器

$scope.openModal = function(){ 
    var item = 'my first item' 
    $scope.showItem(item); 

    //I want to do something here after user clicks 'Click me' button 
}) 

父控制器

$scope.showItem = function(item){ 
    $modal({ 
       template: 'item-modal.html', 
       scope: $scope,     
      }); 
}) 

在我的項目,modal.html

//other html 
<button type="button" class="btn btn-primary" ng-click="confirm()">Click me</button> 

所以我希望孩子能夠了解父母的作用,這是模式的按鈕被點擊。有沒有辦法做到這一點?非常感謝!

回答

1

您可以通過$broadcast監聽事件監聽事件下來父鏈。

// Parent controller 
$scope.confirm = function() { 
    $scope.broadcast("myTestEvent", {'key':'value'}); 
} 


// Child controller 
$scope.$on("myTestEvent", function(data) { 
    console.log("Event from parent fired with data as : " + data); 
}) 
+0

我試圖避免廣播,因爲它不是角度的最佳做法。謝謝您的好意 – BonJon

1

angular-ui modal,對不對?

如果是這樣,$模式API返回一個承諾,當模式與任一$關閉(成功)關閉或$解僱(失敗)解決。請參閱https://angular-ui.github.io/bootstrap/#/modal瞭解更多信息,或者https://docs.angularjs.org/api/ng/service/ $ q瞭解有關承諾的相關信息。

那麼這將非常看起來是這樣的:

$scope.openModal = function(){ 
    var item = 'my first item' 
    $scope.showItem(item).then(function(result) { 
     // DO something with result 
    }); 
}); 

父控制器

$scope.showItem = function(item){ 
    return $modal({ 
       template: 'item-modal.html', 
       scope: $scope,     
      }); 
}) 

在我的項目,modal.html

//other html 
<button type="button" class="btn btn-primary" ng-click="$close(myResult)">Click me</button> 

或使用自己的方法爲ng-click處理程序,它將調用$ scope。$ close以及任何你想要傳回的作爲promise結果。

+0

+1所以如果我想用我自己的方法,無需經過PARAMS在我modal.html,我可以做NG-點擊=「clickme()」 – BonJon

+0

是的,與clickme()方法調用$關閉或$解僱關閉模式結果你想回傳給你的孩子 –

+0

我明白了。但是,promise的返回結果是整個item-modal.html,而不是方法的myResult。你能爲我澄清一下嗎? – BonJon

相關問題