Search code examples
angularjsangularjs-components

How to call parent controller function from within a child component in Angular 1.6.7


I'm trying to invoke a parent method from within a component using ng-click in Angular 1.6.7. Should I instead be using $emit somehow? I am currently attempting to do it via on-click='$ctrl.$parent.myMethod() and it is not invoking the method. Code below, live link here: http://jsbin.com/cenubalola/edit?html,js,output

JS

var app = angular.module('app', []);

app.controller('mainController', ['$scope', function ($scope) {
  $scope.cars = [
    { make: 'civic' },
    { make: 'rav4' }
  ];
  $scope.openEditCar = function(c) {
    $scope.editCar = c;
  };
  $scope.saveCar = function() {
    // save car to db
    alert('saving...');
    $scope.editCar = null; // hide the component
  };
}]);

app.component("editCar", {
    template: 'Editing <input ng-model="$ctrl.editCar.make" /> - <a href="#" ng-click="$ctrl.$parent.saveCar()" onclick="return false;">Save</a>',
    bindings: { editCar: '=' }
});

HTML

<div ng-repeat='c in cars'>
  {{c.make}} - <a href='#' ng-click='openEditCar(c)' onclick='return false;'>Edit</a>
</div>
<edit-car edit-car='editCar' ng-show='editCar'></edit-car>
<div>
  editCar is {{editCar | json}}
</div>

Solution

  • To bind components to parent functions, use expression '&' binding:

    app.component("editCar", {
        template: `Editing <input ng-model="$ctrl.carObj.make" /> - 
                   ̶<̶a̶ ̶h̶r̶e̶f̶=̶"̶#̶"̶ ̶n̶g̶-̶c̶l̶i̶c̶k̶=̶"̶$̶c̶t̶r̶l̶.̶$̶p̶a̶r̶e̶n̶t̶.̶s̶a̶v̶e̶C̶a̶r̶(̶)̶"̶ ̶o̶n̶c̶l̶i̶c̶k̶=̶"̶r̶e̶t̶u̶r̶n̶ ̶f̶a̶l̶s̶e̶;̶"̶>̶S̶a̶v̶e̶<̶/̶a̶>̶
                   <a ng-click="$ctrl.onSave()">Save</a>`,
        bindings: { carObj: '<',
                    onSave: '&' }
    });
    

    Usage:

    <edit-car car-obj='editCar' on-save="saveCar()" ng-show='editCar'>
    </edit-car>
    

    For more information, see AngularJS Developer Guide - Component-based Application Architecture.