Angular 1.6.7 如何从子组件中调用父控制器函数

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

我正在尝试使用 Angular 1.6.7 中的 ng-click 从组件中调用父方法。我应该以某种方式使用 $emit 吗?我目前正在尝试通过 on-click='$ctrl.$parent.myMethod() 进行操作,但它没有调用该方法。下面的代码,在这里生活 link: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>

要将组件绑定到父函数,请使用表达式 '&' 绑定:

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: '&' }
});

用法:

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

有关详细信息,请参阅 AngularJS Developer Guide - Component-based Application Architecture