在这个特殊的情况下,我有什么选项,使这些输入调用函数时,我按下Enter?
Html:
<form>
<input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
<br />
<input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />
</form>
// Controller //
.controller('mycontroller', ['$scope',function($scope) {
$scope.name = '';
$scope.email = '';
// Function to be called when pressing ENTER
$scope.myFunc = function() {
alert('Submitted');
};
}])
我想要一些比给出的答案更可扩展/语义的东西,所以我写了一个指令,以类似于内置ngClass的方式接受javascript对象:
HTML
<input key-bind="{ enter: 'go()', esc: 'clear()' }" type="text"></input>
对象的值在指令作用域的上下文中计算——确保它们被括在单引号中,否则所有函数都将在加载指令时执行(!)
例如:
Esc: 'clear()'而不是Esc: clear()
Javascript
myModule
.constant('keyCodes', {
esc: 27,
space: 32,
enter: 13,
tab: 9,
backspace: 8,
shift: 16,
ctrl: 17,
alt: 18,
capslock: 20,
numlock: 144
})
.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("keydown keypress", function (event) {
if (bindings.hasOwnProperty(event.which)) {
scope.$apply(function() {
scope.$eval(bindings[event.which]);
});
}
});
};
}]);
我想要一些比给出的答案更可扩展/语义的东西,所以我写了一个指令,以类似于内置ngClass的方式接受javascript对象:
HTML
<input key-bind="{ enter: 'go()', esc: 'clear()' }" type="text"></input>
对象的值在指令作用域的上下文中计算——确保它们被括在单引号中,否则所有函数都将在加载指令时执行(!)
例如:
Esc: 'clear()'而不是Esc: clear()
Javascript
myModule
.constant('keyCodes', {
esc: 27,
space: 32,
enter: 13,
tab: 9,
backspace: 8,
shift: 16,
ctrl: 17,
alt: 18,
capslock: 20,
numlock: 144
})
.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("keydown keypress", function (event) {
if (bindings.hasOwnProperty(event.which)) {
scope.$apply(function() {
scope.$eval(bindings[event.which]);
});
}
});
};
}]);
FWIW -这是一个我用于基本确认/警报引导模式的指令,不需要<form>
(只需切换出jQuery的点击动作,无论你喜欢什么,并添加data-easy-dismiss到你的模式标签)
app.directive('easyDismiss', function() {
return {
restrict: 'A',
link: function ($scope, $element) {
var clickSubmit = function (e) {
if (e.which == 13) {
$element.find('[type="submit"]').click();
}
};
$element.on('show.bs.modal', function() {
$(document).on('keypress', clickSubmit);
});
$element.on('hide.bs.modal', function() {
$(document).off('keypress', clickSubmit);
});
}
};
});