OneChillDude
OneChillDude

Reputation: 8006

Prevent parent ng-submit with a child element directive?

In the following angular form I would like to prevent ng-submit if we are currently editing a field called tags, which is special, because using enter on tags submits the tag, not the form.

<form ng-submit="submit()">
  <input type="foo" />
  <input type="tags" ng-keyup="submitTag($event)" />
  <input type="submit" />
</form>

And in angular

$scope.submit = function($event) {
  if ($event.keyCode == 13) {
    $event.stopPropagation();
    return false;
    // What do I have to do?

  }
};

I've also tried binding the input to ng-submit. How do I prevent Angular from running the submit code if keyCode == 13 and the user is editing tags?

Upvotes: 0

Views: 888

Answers (3)

gmustudent
gmustudent

Reputation: 2209

One alternative to creating a new directive is to just use angulars ngKeydown. Note: Do not use ngKeyup b/c that event fires after ngSubmit.

Template:

<input type="text" ng-model="x" ng-keydown="$event.which === 13 ? fn($event) : null;" />

Controller:

$scope.fn = function($event)
{
  if(_.isObject($event))
  {
    $event.preventDefault();
  }

  // Continue with whaterver this fn is supposed to do
};

Upvotes: 0

user1625066
user1625066

Reputation:

You can accomplish this by moving your submit button outside your form as shown below

<form name="myForm">
      <input type="foo" />
      <input type="tags" ng-keyup="submitTag($event)" />
    </form>
    <button ng-click="submit()">Submit</button>
  </body>

$scope.submit = function($event) {
    if (!$scope.myForm.$valid) {
             return;
        }

    alert('submit form');
  };

  $scope.submitTag = function(event){

    alert('submit tag');
  };

Here is a working plunker

http://plnkr.co/edit/7G22wcR9UsbIsH9LtT11?p=preview

Upvotes: 0

Rob
Rob

Reputation: 1860

Need to create a directive for this:

app.directive('tags',function() {
    return {
        restrict:'A',
        link: function(scope,element,attr) {
            element.on('keydown',function(e) {
                if (e.which == "13") {
                    e.preventDefault();
                }
            });
        }
    }
});

HTML

<input type="text" tags>

Upvotes: 1

Related Questions