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

时间:2018-01-14 19:42:43

标签: angularjs angularjs-components

我试图在Angular 1.6.7中使用ng-click从组件中调用父方法。我应该以某种方式使用$emit吗?我目前正在尝试通过on-click='$ctrl.$parent.myMethod()进行此操作,而不是调用该方法。以下代码,实时链接: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>

1 个答案:

答案 0 :(得分:3)

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

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