Dailycode.info

Short solution for short problems

AngularJS: trigger click on 'Enter' in input

Some time ago I wrote a directive to get the Enter key to trigger a function on the controller. It looks like this:

 .directive('keyBind', ['keyCodes', function (keyCodes) {
        function map(obj) {
            var mapped = {};
            for (var key in obj) {
                var action = obj[key];
                if (keyCodes.hasOwnProperty(key)) {
                    mapped[keyCodes[key]] = action;
                }
            }
            return mapped;
        }
        return function (scope, element, attrs) {
            var bindings = map(scope.$eval(attrs.keyBind));
            element.bind("keypress", function (event) {
                if (bindings.hasOwnProperty(event.which)) {
                    scope.$apply(function ()
                    {
                        console.log(event);
                        scope.$eval(bindings[event.which]);
                    });
                }
            });
        };
    }]);

and it used like this:

<input type="text" class="form-control" data-ng-model="playerText" name="player" placeholder="Speler naam" aria-describedby="basic-addon1" key-bind="{ enter: 'addPlayer()'}">

But this can be a lot easier using the ng-keyup directive by angular:

<input ng-keyup="$event.keyCode == 13 && $ctrl.save()" ng-model="$ctrl.editName" placeholder="name" class="form-control" />

It's the same method thats called on this button:

<button type="button" ng-click="$ctrl.save()" class="btn btn-primary">Save</button>

So in stead of writing my own directive, we can just use ng-keyup.


On leave and enter hit events in UITextField (iOS)

If you want to catch the event when a user leaves a text box and has changed something, or when he presses enter in the text box itself, you will need to do 2 things:

- For the leave it's very easy, Apple already prepared this event for you. Use the Editing Did End Action and connect it to your controller's implementation file:

 

But now you also want to capture the event that occurs when the user presses enter in the textfield.

For this we start by adding the UITextFieldDelegate protocol in the controller.h:

@interface PhotoTakerViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPopoverControllerDelegate, UITextFieldDelegate >

next we implement it like this:

- (BOOL) textFieldShouldReturn:(UITextField *)textField

{

    ...Do something

    return YES;

}