Reputation: 799
I am trying to pop a modal on the parent controller and do something to the child after use click a button
For example, child controller
$scope.openModal = function(){
var item = 'my first item'
$scope.showItem(item);
//I want to do something here after user clicks 'Click me' button
})
Parent controller
$scope.showItem = function(item){
$modal({
template: 'item-modal.html',
scope: $scope,
});
})
In my item-modal.html
//other html
<button type="button" class="btn btn-primary" ng-click="confirm()">Click me</button>
So I want the child be able to know parent's action which is the modal button being clicked. Is there a way to do this? Thanks a lot!
Upvotes: 0
Views: 63
Reputation: 2953
angular-ui modal, right ?
If so, the $modal api returns a promise resolving when the modal is closed with either $close ( success ) or $dismiss ( failure ). See https://angular-ui.github.io/bootstrap/#/modal for more info, or https://docs.angularjs.org/api/ng/service/$q for infos about promises.
So this would pretty much looks like this :
$scope.openModal = function(){
var item = 'my first item'
$scope.showItem(item).then(function(result) {
// DO something with result
});
});
Parent controller
$scope.showItem = function(item){
return $modal({
template: 'item-modal.html',
scope: $scope,
});
})
In my item-modal.html
//other html
<button type="button" class="btn btn-primary" ng-click="$close(myResult)">Click me</button>
or use your own method as the ng-click handler which would call $scope.$close with whatever you want to pass back as the promise result.
Upvotes: 1
Reputation: 1776
You can listen to events via $broadcast
to listen to events down the parent chain.
// 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 );
})
Upvotes: 1