Reputation: 7532
I have a controller nested in another controller.
<div ng-controller="manufacturerController" ng-cloak>
<div ng-controller="contractController" ng-cloak>
<div data-ng-if="item" class="panel panel-default">
<div class="panel-heading text-center">
<span class="h3">Contract</span>
</div>
</div>
</div>
<button data-ng-if="item && !ajaxOut" class="btn btn-success" data-ng-click="saveItem()">Save</button>
</div>
saveItem() is called via the button and the code is in the manufacturerController:
$scope.saveItem = function () {
$scope.ajaxOut = true;
$scope.saveContracts();
};
But the function saveContracts() is in the contractController. I want to call the contractController.saveContracts() from manufacturerController.saveItem().
According to here I should be able to call the parent method fine: How to call a function from another controller in angularjs?
But the save is freezing the browser. What am I doing wrong and how do I fix it?
Upvotes: 3
Views: 3097
Reputation: 48968
One way is broadcasting an event on scope:
function ParentController($scope)
{
$scope.$broadcast('someEvent', args);
}
function ChildController($scope)
{
$scope.$on('someEvent', function(event, args) {});
// another controller or even directive
}
Scope Events Propagation
Scopes can propagate events in similar fashion to DOM events. The event can be broadcasted to the scope children or emitted to scope parents.
For more information, see Can one controller call another?
Upvotes: 6
Reputation: 4888
Look up "$on $emit $broadcast angularjs". Tons and tons of examples out there.
(As I said previously in my comment, you don't want controllers to have any knowledge of each other. One dispatches an event/notification, another hears it, sort of like somebody you don't know just standing up in a room and shouting a name you're interested in).
Each is used for a different context. Depending on what you're doing, you might use one or the other. Understanding each of those is super important to the AngularJS developer (and the overall concept to any UI dev).
Upvotes: 1
Reputation: 941
You can use $broadcast from the parent to a child:
function ParentCntl($scope) {
$scope.msg = "";
$scope.get = function(){
$scope.$broadcast ('someEvent');
return $scope.msg;
}
}
function ChildCntl($scope) {
$scope.$on('someEvent', function(e) {
$scope.$parent.msg = $scope.get();
});
$scope.get = function(){
return "xyz";
}
}
Upvotes: 1