Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a child component function from parent component in Angular 1.5

Tags:

angularjs

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 ?

like image 851
StrugglingCoder Avatar asked Jul 13 '17 10:07

StrugglingCoder


People also ask

How do you call parent component to child component?

Calling parent component method To call a parent component method from the child component, we need to pass the changeName() method as a prop to the child component and access it as a props data inside the child component.

How do you style a child component from the parent component?

use @Component to add css class to host element and set encapsulation to none. Then reference that class which was added to the host within the components style. css. scss This will allow us to declare styles which will only affect ourselves and our children within scope of our class.


Video Answer


1 Answers

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
});
like image 90
Freego Avatar answered Nov 22 '22 11:11

Freego