ng-keypress事件未从电子邮件输入标记触发

时间:2014-02-03 23:15:17

标签: javascript angularjs

我正在尝试使用角度JS,我正在努力让ng-keypress事件正常运行。我的HTML看起来像这样:

<form accept-charset="UTF-8" action="/orders" class="new_order" id="new_order" method="post" ng-controller="OrderCreateController">
   <div class="new-invitee"><input id="new_invitee" name="new_invitee" ng-keyup="addNewInvitee($event)" placeholder="Add email addresses here..." required="required" type="email" /></div>
</form>

控制器看起来像:

  app.controller('OrderCreateController', function($scope, $http, $element) {
    $scope.invitees = [];
    return $scope.addNewInvitee = function($event) {
      var el, isValid;
      isValid = $event.target.validity.valid;
      el = $($event.target.parentElement);
      el.toggleClass('valid', isValid);
      el.toggleClass('invalid', !isValid);
      if ($event.which !== 13 || !isValid) {
        return;
      }
      $scope.invitees.push({
        name: $event.target.value
      });
      return $event.preventDefault();
    };
  });

但控制器方法永远不会被调用。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您有两种选择。

选项1:删除&#39;行动=&#34; /订单&#34; &#39;从您的表单标签,所有运行正常。

选项2:重写您的代码:

app.controller('OrderCreateController', function($scope, $http, $element) {
  $scope.invitees = [];
  return $scope.addNewInvitee = function($event) {
    $event.preventDefault(); // stripped return from the preventDefault and moved to the top. 
    var el, isValid;
    isValid = $event.target.validity.valid;
    el = angular.element($event.target.parentElement);
    el.toggleClass('valid', isValid);
    el.toggleClass('invalid', !isValid);
    if ($event.which !== 13 || !isValid) {
      return;
    }
    $scope.invitees.push({
      name: $event.target.value
    });
    console.log("I just ran!", $scope.invitees); // Sanity check
  };
});

这两个选项都在我的运行中运行得很好,希望这一切都适合你。

祝你好运:)