Angular UI - 为按键绑定和取消绑定

时间:2013-05-03 07:05:27

标签: angularjs angularjs-directive angular-ui

我想在用户点击复选框时绑定/取消绑定按键。我尝试编写一些代码,但在javascript控制台中没有错误就完全没有工作。

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); }
}

你的建议?

1 个答案:

答案 0 :(得分:3)

你可以这样做:

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');
    }
});

请参阅working jsfiddle here