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

时间:2015-01-08 19:16:40

标签: javascript angularjs angularjs-directive angularjs-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");
            }
        }
    }
});

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

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

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

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

});

基本上我希望click事件能够“传递”指令和控制器。我希望两个事件处理程序都能触发上一次按钮点击。

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

1 个答案:

答案 0 :(得分:2)

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

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

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

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

所以你可以在链接功能中做到这一点:

 $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>

<强>演示

&#13;
&#13;
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");
      }
    }
  }
});;
&#13;
<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>
&#13;
&#13;
&#13;