如何在指令和控制器中处理模板 ng-click?

How do you handle a template ng-click in both a directive and controller?

我有一个带有模板的指令(基本上是两个带有 ng-click 的按钮)。

app.directive('foo', function(){
    return {
        scope: {
            onNext: "=",
            onPreviousClick: "="
        },
        restrict: "E",
        template: "<button ng-click='onPreviousClick($event)'>Prev</button> <button ng-click='onNextClick($event)'>Next</button>",
        link: function($scope){

            $scope.onPreviousClick = function(){
               console.log("Prev click event from directive");
            }
            $scope.onNextClick = function(){
               console.log("Next click event from directive");
            }
        }
    }
});

现在,当我使用该指令时,我想将点击处理程序设置为在控制器中工作。

<foo on-previous-click="ctrl.onPreviousClick($event)"></foo>

app.controller("myController", function($scope){

    this.onPreviousClick = function(){
       console.log("Prev click from the controller.");
    }

});

基本上我希望点击事件 "pass-through" 指令和控制器。我希望两个事件处理程序都为上一个按钮点击触发。

但我只能让一个或另一个点击处理程序工作。如果我注释掉我的指令处理程序,控制器就会工作,反之亦然。

理想情况下,您应该使用函数绑定 & 而不是双向绑定,并且也只从指令处理程序进行调用。

return {
    scope: {
        onNext: "&",
        onPreviousClick: "&"
    },

并通过键值对将事件传递给绑定的处理程序,即

    $scope.onPrev({$event: $event });

因此您可以在 link 函数中执行此操作:

 $scope.onPrevClick = function($event) {
    console.log("Prev click event from directive");
    $scope.onPrev({
      $event: $event
    });
  }

或模板本身。

 <button ng-click='onPrevClick($event);onPrev({$event:$event})'>Prev</button>

演示

angular.module('app', []).controller('ctrrl', function($scope) {
  this.onPreviousClick = function() {
    console.log("Prev click from the controller.");
  }
  this.onNextClick = function() {
    console.log("Next click from the controller.");
  }
}).directive('foo', function() {
  return {
    scope: {
      onNext: "&",
      onPrev: "&"
    },
    restrict: "E",
    template: "<button ng-click='onPrevClick($event)'>Prev</button> <button ng-click='onNextClick($event); onNext({$event:event})'>Next</button>",
    link: function($scope) {

      $scope.onPrevClick = function($event) {
        console.log("Prev click event from directive");
        $scope.onPrev({
          $event: $event
        });
      }
      $scope.onNextClick = function() {
        console.log("Next click event from directive");
      }
    }
  }
});;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="app" ng-controller="ctrrl as ctrl">
  <foo on-prev="ctrl.onPreviousClick($event)" on-next="ctrl.onNextClick($event)"></foo>
</div>