StrugglingCoder
StrugglingCoder

Reputation: 5021

Call a child component function from parent component in Angular 1.5

In my parent component's template, there is a nested component.

<div class="inner" ng-show="!vm.loading">
    <div class="info-panel">
        <h3 id="basePrice">Current Cost</h3>
        <p>
            <small>
                <a href role="button" data-toggle="modal" ng-click="vm.openCostsModal()">See Details</a>
            </small>
        </p>
    </div>
    ......
    ......
    <pricingcalculation></pricingcalculation>

This <pricingcalculation></pricingcalculation> is the nested component. And it's definition looks like :

(function () {
    "use strict";
    angular.module("app")
        .component("pricingcalculation", {
            transclude: true,
            templateUrl: "/static/angtemplates/pricing-calculation.html",
            controllerAs: "vm",
            controller: ["$rootRouter", function ($rootRouter) {
                var vm = this;
                vm.openCostsModal = function () {
                    vm.costItems = [];
                    vm.projectedCostItems = [];
                    vm.totalOfCostItems = 0;
                    .....
                    .....

So on that See Details button click which is defined on parent's template

I want the child component's function openCostsModal() to be called.

How to do that ?

Upvotes: 8

Views: 7370

Answers (1)

Freego
Freego

Reputation: 466

You can use $broadcast in your parent to broadcast an event and use $onin your child to listen to it.

Like so :

In parent :

$scope.$broadcast("someEvent"); 

In child :

$scope.$on("someEvent",function(){
  //do stuff here
});

Upvotes: 15

Related Questions