javascript 如何在 AngularJS 中观察自定义事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14925728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:57:11  来源:igfitidea点击:

How to observe custom events in AngularJS?

javascriptangularjsangularjs-directive

提问by ValeriiVasin

Simple example: I have a textarea and want to provide additional behavior to it: do something on enterkey and go to next line on shift + enter

简单示例:我有一个 textarea 并希望为它提供额外的行为:enter按键执行某些操作并转到下一行shift + enter

I suppose that I should provide additional directive to add that behavior. And I've done this: http://jsbin.com/oruvuy/1/edit

我想我应该提供额外的指令来添加该行为。我已经这样做了:http: //jsbin.com/oruvuy/1/edit

P.S. One hackie thing seems strange for me: I invoke $digest()manually. Is it ok? Any thoughts?

PS 一件 hackie 的事情对我来说似乎很奇怪:我$digest()手动调用。可以吗?有什么想法吗?

JS:

JS:

angular.module('Chat', [])
  .directive('enterSubmit', function () {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        var submit;

        $(element).on({
          keydown: function (e) {
            submit = false;

            if (e.which === 13 && !e.shiftKey) {
              submit = true;
              e.preventDefault();
            }
          },

          keyup: function () {
            if (submit) {
              scope.$eval( attrs.enterSubmit );

              // flush model changes manually
              scope.$digest();
            }
          }
        });
      }
    };
  });

function ChatCtrl($scope) {
  $scope.messages = [{
    text: 'Sample Message',
    datetime: new Date()
  }];

  $scope.add = function () {
    $scope.messages.push({
      text: $scope.message,
      datetime: new Date()
    });
    $scope.message = '';
  };

  $scope.message = '';
}
<body ng-controller="ChatCtrl">

  <h1>Leave message:</h1>
  <form>
    <div class='hint'>Click &lt;Enter&gt; to submit :)</div>
    <textarea
      cols="30"
      rows="5"
      ng-model="message"
      enter-submit='add()'
    ></textarea>
    <br />
    <button type="submit" ng-click="add()">Send message!</button>
  </form>

  <h3>Messages list:</h3>
  <table>
    <tr>
      <th>Text</th>
      <th>Date</th>
    </tr>
    <tr ng-repeat="message in messages">
      <td class='text'>{{message.text}}</td>
      <td class='date'>{{message.datetime | date:"HH:mm:ss"}}</td>
    </tr>
  </table>

</body>

But is it correct way to do that?

但这样做是正确的方法吗?

采纳答案by jingman

Yes, binding events in the directive's linking function is exactly what you want to do.

是的,指令的链接函数中的绑定事件正是您想要做的。

Calling $digest is not hacky - the messages in your example are being added to the model on keyup, and Angular won't digest those changes until something tells it to. It will actually be digested on the next keydown, but since you need the $digest to happen after your keyup, you're having to call it manually.

调用 $digest 并不笨拙 - 您示例中的消息正在添加到模型中keyup,并且 Angular 不会消化这些更改,直到有人告诉它。它实际上会在 next 被消化keydown,但由于您需要在您的 之后发生 $digest keyup,因此您必须手动调用它。