anhtran
anhtran

Reputation: 2044

Angular UI - Bind and unbind for keypress

I want to bind/unbind the keypress when user clicks to the checkbox. I tried to code a bit but not work at all without error in javascript console.

HTML

<textarea name="message" ng-model="message" ui-keypress="btnEnter"></textarea>
<input type="checkbox" ng-click="bindKeyEnter($event)">

JS

function MyCtrl($scope) {
     $scope.btnEnter = {};

     $scope.bindKeyEnter = function(e) {
         var checkbox = e.target;
         $scope.btnEnter = checkbox.checked ? {enter: 'sendMessage()'} : {}
     };

     $scope.sendMessage = function() { console.log($scope.message); }
}

Your suggestion?

Upvotes: 1

Views: 1984

Answers (1)

joakimbeng
joakimbeng

Reputation: 877

You could do it like this:

Html:

<div ng-controller="TstCtrl">
    <input ui-keypress="{enter: enter}" />
    <input type="checkbox" ng-model="doOnEnter" />
</div>

Javascript:

app.controller('TstCtrl', function ($scope) {
    $scope.enter = function () {
        if ($scope.doOnEnter)
            realOnEnter();
    };

    function realOnEnter() {
        console.log('On enter');
    }
});

See working jsfiddle here

Upvotes: 3

Related Questions