Calling a function defined in one controller from another depends on the version of Angular you’re working with. Here’s a breakdown of how this communication evolves from AngularJS (v1.x) to the latest Angular (v2+ and beyond).
In AngularJS, controllers do not directly interact with each other. Instead, communication is achieved using event-based mechanisms like $emit, $broadcast, and $on.
Example: Using $rootScope to trigger functions across controllers
app.controller('One', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.parentmethod = function() {
// Task to perform
console.log("Parent method called");
};
$rootScope.$on("CallParentMethod", function() {
$scope.parentmethod();
});
}]);
app.controller('Two', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod");
};
}]);
Angular (from v2 onward) is built on a component-based architecture, and controllers are replaced by components. The standard way to invoke a method in another component involves shared services, @ViewChild, or Output events, depending on the component hierarchy.
Scenario 1: Parent-Child Communication
Use @ViewChild() to call a child component’s method from the parent.
// child.component.ts
@Component({
selector: 'app-child',
template: `Child Component
`
})
export class ChildComponent {
public callMe() {
console.log('Child method called');
}
}
// parent.component.ts
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
@ViewChild(ChildComponent) child!: ChildComponent;
triggerChild() {
this.child.callMe();
}
}
Scenario 2: Unrelated Components or Services Communication
If the components are not in a parent-child relationship, use a shared service with a Subject.
// shared.service.ts
@Injectable({ providedIn: 'root' })
export class SharedService {
private actionSource = new Subject();
action$ = this.actionSource.asObservable();
triggerAction() {
this.actionSource.next();
}
}
// sender.component.ts
export class SenderComponent {
constructor(private sharedService: SharedService) {}
trigger() {
this.sharedService.triggerAction();
}
}
// receiver.component.ts
export class ReceiverComponent implements OnInit {
constructor(private sharedService: SharedService) {}
ngOnInit() {
this.sharedService.action$.subscribe(() => {
this.targetMethod();
});
}
targetMethod() {
console.log('Receiver method called');
}
}
Work with our skilled Angular developers to accelerate your project and boost its performance.
Hire Angular Developers