如何在angularjs中绑定多个自定义事件?

时间:2017-03-08 07:27:27

标签: angularjs custom-events

我需要在angularjs(1.x)中绑定自定义事件,我尝试使用以下代码

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://www.polymer-project.org/components/polymer/polymer.html" rel="import">
<link href="https://www.polymer-project.org/components/paper-button/paper-button.html" rel="import">
<div ng-app="demo-app">
    <div ng-controller="DemoController">
        <template bind-angular-scope is="auto-binding">
          <paper-button raised on-tap="{{clickMe}}" on-mouseover="{{mouseOver}}">click me</paper-button>
        </template>
        <pre><code>{[{text}]}</code></pre>
    </div>
</div>

脚本

<script>
angular.module('demo-app', [])
  .config(function ($interpolateProvider) {
      $interpolateProvider.startSymbol('{[{').endSymbol('}]}');
  })
  .directive('bindAngularScope', function () {
      return {
          restrict: 'A',
          link: function (scope, element, attrs) {
              for (k in scope) {
                  if (!element[0][k]) {
                      element[0][k] = scope[k];
                  }
              }
          }
      }
  })
  .controller('DemoController', function ($scope) {
      $scope.text = '';
      $scope.clickMe = function () {
          $scope.text += '\nyou clicked me!!';
          $scope.$apply();
      };
      $scope.mouseOver = function () {
          $scope.text += '\nyou hovered me!!';
          $scope.$apply();
      }
  });
</script>

这不起作用。您能否指出我的问题或是否有任何解决方案来绑定自定义事件(多个)?我们是否需要为每个人创建一个自定义指令?

注意:

以上代码来自以下网址

How to bind custom events in AngularJS?

提前致谢!

1 个答案:

答案 0 :(得分:0)

angular.module('demo-app', [])
  .config(function ($interpolateProvider) {
      $interpolateProvider.startSymbol('{[{').endSymbol('}]}');
  })
  .directive('bindAngularScope', function () {
      return {
          restrict: 'A',
          link: function (scope, element, attrs) {
              for (k in scope) {
                  if (!element[0][k]) {
                      element[0][k] = scope[k];
                  }
              }

               elem.bind('click', function() {
                /* Place your click logic here * /
                 });
          }
      }
  })