OneChillDude OneChillDude - 1 day ago 4
AngularJS Question

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?

Rob Rob
Answer

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