Open ui.boostrap typeahead dropdown up - angularjs

I trying to open the typeahead boostrap-ui angular upwards.
Here is my code example:
index.html
<div class="dropup" ng-controller="TypeaheadCtrl">
<input type="text" ng-model="asyncSelected" placeholder="> Select issue" typeahead="address for address in getLocation($viewValue)" typeahead-loading="loadingLocations" class="form-control inline-edit-form">
<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>
</div>
app.js
app.controller('TypeaheadCtrl', function($scope, $http) {
$scope.selected = undefined;
$scope.getLocation = function (val) {
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {
params: {
address: val,
sensor: false
}
}).then(function (response) {
return response.data.results.map(function (item) {
return item.formatted_address;
});
});
};
});
Because I have the "dropdown" at the bottom, how can I reverse the opening?

Had the same problem. Although it's not the most elegant solution this fixed it for me:
div.dropup ul {
bottom:100% !important;
top:auto !important;
}

Minor change i had to make (notice the class name is dropdown-menu and not dropup)
#txtSearch ul.dropdown-menu {
bottom:100% !important;
top:auto !important;
}
I had to #txtSearch simple because i have other dropdown-menu that needs to drop down.

Related

Angular set pristine doesn't work as expected

I am trying to create a custom validation on one of my inputs. Everything works as expected but the error css class is still applied. I tried with $setPristine()
and $setUntouched() first on the input (didn't work) and then on the form. The perfect solution will be if I can reset the style in ng-change.
self.changeTransferNumber = function () {
if (validateRoutingNumber(self.bankTransferNumber)) {
self.bankInfoForm.bankTransferNumber.$error.validateTransferNumber = false;
self.bankInfoForm.$setPristine();
self.bankInfoForm.$setUntouched();
} else {
self.bankInfoForm.bankTransferNumber.$error.validateTransferNumber = true;
}
}
<form name="$ctrl.bankInfoForm" novalidate ng-submit="$ctrl.saveInfo($event)">
<input type="text" ng-model="$ctrl.bankTransferNumber" ng-disabled="$ctrl.disableTextEdit" name="bankTransferNumber" required ng-change ="$ctrl.changeTransferNumber()"/>
<div ng-messages="$ctrl.bankInfoForm.bankTransferNumber.$error" ng-show="$ctrl.bankInfoForm.bankTransferNumber.$dirty">
<div ng-message = "validateTransferNumber" >The transfer number is not correct</div>
</div>
</form>
You need to pass your Form name in html:-
<form role="form" name="Form" id="Form" ng-submit="Form.$valid && saveFormData($event,Form)" novalidate autocomplete="off">
in Your controller /js file :-
$scope.saveFormData = function (event,myForm) {
//after your whole logic
....
//to reset form
myForm.$setPristine();
}
What i understand from this question....
Why not create a custom validator using a directive? This way it's easily reusable.
(function() {
'use strict';
angular.module('myApp', []);
angular.module('myApp').controller('MyController', MyController);
MyController.$inject = [];
function MyController() {
var main = this;
main.routingNumber = '2';
}
angular.module('myApp').directive('validateRoutingNumber', function() {
return {
restrict: 'A',
require: {ngModel: ''},
bindToController: true,
controllerAs: '$dir',
controller: function() {
var $dir = this;
$dir.$onInit = function() {
createValidators();
};
function createValidators() {
$dir.ngModel.$validators.routingNumber = function(modelValue, viewValue) {
var value = modelValue || viewValue;
//without this if-else it would become a required field
if (value) {
return value.toString().length >= 3 && value.toString().indexOf('1') !== -1;
} else {
return true;
}
}
}
}
};
});
}());
input.ng-invalid {
border: 1px red solid;
background-color: red;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyController as main">
<form name="frmMain">
<input type="text" ng-model="main.routingNumber" name="routingNumber" validate-routing-number>
<span ng-if="frmMain.routingNumber.$invalid">Needs to have at least three characters and at least one '1'</span>
</form>
</div>
</body>

Save Form data from Popover in Angularjs

var App = angular.module('myApp', []);
App.controller('myPopoverCtrl',
function($scope){
$scope.myPopover = {
isOpen: false,
open: function open() {
$scope.myPopover.isOpen = true;
},
close: function close() {
// alert('hi');
$scope.myPopover.isOpen = false;
}
};
$scope.SaveNotes = function() {
console.log('hi');
console.log($scope.noteText);
//getting undefined here
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "App">
<a uib-popover-template="'AddNote.html'"
popover-title="AddNote"
popover-trigger="'outsideClick'"
ng-controller="myPopoverCtrl"
popover-is-open="myPopover.isOpen"
ng-click="myPopover.open()">Add
</a>
</div>
<script type="text/ng-template" id="AddNote.html">
<div>
<textarea class="form-control height-auto"
ng-model="noteText"
placeholder="This is a new note" ></textarea>
<input class="btn btn-outline btn-primary"
type="button"
ng- click="SaveNotes();" value="Save">
</div>
</script>
I have web a page where i have a button and when click the button popover appears.In that popover i have textarea but when i click save button i want get the text in my controller but i am getting undefined using $scope.modelname
How can i get that data?
I think you want to use a modal rather than a popover like so, as a popover is really just to display text :-
var modalInstance = $modal.open({
animation: $rootScope.animationsEnabled,
templateUrl: 'views/myTemplate.html',
size: 'md'
}).result.then(function(result) {
$scope.result = result;
});
This is what it's designed for more info here.

Directive-validator doesn't catch empty field but filled field

I have the following AngularJS code. It should check if input field is empty when I press Submit button. Submit button broadcasts custom event that directive successfully catches. But it doesn't work when field is empty. It reaches ctrl.$parsers.unshift when I start typing and my field becomes theForm.name.$invalid===true. It seems to work the opposite way.
define(['angular'], function (angular) {
"use strict";
var requiredValidator = angular.module('RequiredValidator', []);
requiredValidator.directive('validateRequired', function () {
var KEY_ERROR = "required";
return {
scope: {
validateRequired: '=validateRequired'
},
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
function validate(value) {
var valid = !value || value === '' || value === null;
ctrl.$setValidity(KEY_ERROR, valid);
return value;
}
scope.$on('validateEvent', function (event, data) {
if (scope.validateRequired.$submitted) {
console.log("Reachable block when submitted");
ctrl.$parsers.unshift(function (value) {
console.log("Unreachable when input is empty");
return validate(value);
});
ctrl.$formatters.unshift(function (value) {
return validate(value);
});
}
});
}
};
});
return requiredValidator;
});
Form field snippet:
<div>
<input type="text" name="name"
data-ng-class="{ error : theForm.name.$invalid}"
data-ng-model="customer.name"
data-validate-required="theForm">
<span data-ng-show="theForm.name.$invalid" class="error">{{getInputErrorMessage(theForm.name.$error)}}</span>
</div>
You actually don't need such a complex directive for your szenario. You could also handle the logic within a controller like so:
var app = angular.module('form-example', ['ngMessages']);
app.controller('FormCtrl', function($scope) {
var vm = this;
vm.submit = function(form) {
if (form.$invalid) {
angular.forEach(form.$error.required, function(item) {
item.$dirty = true;
});
form.$submitted = false;
} else {
alert('Form submitted!');
}
};
});
label,
button {
display: block;
}
input {
margin: 5px 0;
}
button {
margin-top: 10px;
}
form {
margin: 10px;
}
div[ng-message] {
margin-bottom: 10px;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-messages.js"></script>
<form ng-app="form-example" name="myForm" ng-controller="FormCtrl as vm" novalidate="" ng-submit="vm.submit(myForm)">
<label for="username">Username</label>
<input id="username" type="text" name="username" ng-model="vm.username" required="" />
<div ng-messages="myForm.username.$error" ng-if="myForm.username.$dirty" role="alert">
<div ng-message="required">Username is required</div>
</div>
<label for="email">E-Mail</label>
<input id="email" type="email" name="email" ng-model="vm.email" required="" />
<div ng-messages="myForm.email.$error" ng-if="myForm.email.$dirty" role="alert">
<div ng-message="required">E-Mail is required</div>
<div ng-message="email">Your E-Mail is not valid</div>
</div>
<button type="submit">Send</button>
</form>
This requires to use at least AngularJS version 1.3.0 since I use the $submitted property of the internal FormController. For more information check the documentation on the FormController. I also use ngMessages which was also introduced in 1.3. This is pretty helpful if you want to display messages in forms in respect to errors.

Angular datetimepicker issue

I'm trying to create a multi step form with angular, that contains a datetimepicker, using ui.router and ui.angular.datetimepicker.
i've got the form all working and loading the picker ok, but I'm getting a strange error:
Uncaught TypeError: object is not a functionangular-animate.js:938 (anonymous function)
2angular.js:11607 TypeError: Cannot read property 'then' of undefined
at Object.ngIfWatchAction [as fn] (angular.js:21974)
at Scope.$get.Scope.$digest (angular.js:14243)
at Scope.$get.Scope.$apply (angular.js:14506)
at HTMLSpanElement.<anonymous> (angular.js:21443)
at HTMLSpanElement.eventHandler (angular.js:3014)angular.js:11607 (anonymous function)angular.js:8557 $getangular.js:14261 $get.Scope.$digestangular.js:14506 $get.Scope.$applyangular.js:21443 (anonymous function)angular.js:3014 eventHandler
whenever I select the dates on the form. I'm a noob to angular and trying to work out what this is - I'm adding the angular-animate.js file from Google's hosted libraries so this is ok - can anyone help?
I have the following app:
angular.module('formApp', ['ngAnimate', 'ui.router', 'ui.bootstrap', 'ui.bootstrap.datetimepicker' ])
// configuring our routes
// =============================================================================
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show our basic form (/form)
.state('form', {
url: '',
templateUrl: 'views/home.html',
controller: 'formController'
})
// nested states
// each of these sections will have their own view
// url will be nested (/form/profile)
.state('form.date', {
url: '',
templateUrl: 'views/form-date.html'
})
// url will be /form/interests
.state('form.address', {
url: '/',
templateUrl: 'views/form-interests.html'
})
// url will be /form/payment
.state('form.payment', {
url: '/',
templateUrl: 'views/form-payment.html'
})
// url will be /form/payment
.state('form.appointments', {
url: '/appointments',
});
// catch all route
// send users to the form page
$urlRouterProvider.otherwise('/');
})
I have the following home.html:
<div id="form-container">
<div class="page-header text-center">
<!-- the links to our nested states using relative paths -->
<!-- add the active class if the state matches our ui-sref -->
<div id="status-buttons" class="text-center">
<a ui-sref-active="active" ui-sref=".date"><span>1</span> Date</a>
<a ui-sref-active="active" ui-sref=".address"><span>2</span> Address</a>
<a ui-sref-active="active" ui-sref=".payment"><span>3</span> Payment</a>
</div>
</div>
<!-- use ng-submit to catch the form submission and use our Angular function -->
<form id="signup-form" ng-submit="processForm()">
<!-- our nested state views will be injected here -->
<div id="form-views" ui-view></div>
</form>
</div>
and then to inject the form-date.html:
<h3>When would you like a helper?</h3>
<datetimepicker data-ng-model="formData.date"
data-datetimepicker-config="{ startView:'day', minView:'hour' }" />
<div> You've selected: {{formData.date}}</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
<a ui-sref="form.payment" class="btn btn-block btn-info">
Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
</a>
</div>
I'm using a custom CSS for the animation styling styling:
/* ANIMATION STYLINGS
============================================================================= */
#signup-form { position:relative; min-height:300px; overflow:hidden; padding:30px; }
#form-views { width:auto; }
/* basic styling for entering and leaving */
/* left and right added to ensure full width */
#form-views.ng-enter,
#form-views.ng-leave { position:absolute; left:30px; right:30px;
transition:0.5s all ease; -moz-transition:0.5s all ease; -webkit-transition:0.5s all ease;
}
/* enter animation */
#form-views.ng-enter {
-webkit-animation:slideInRight 0.5s both ease;
-moz-animation:slideInRight 0.5s both ease;
animation:slideInRight 0.5s both ease;
}
/* leave animation */
#form-views.ng-leave {
-webkit-animation:slideOutLeft 0.5s both ease;
-moz-animation:slideOutLeft 0.5s both ease;
animation:slideOutLeft 0.5s both ease;
}
/* ANIMATIONS
============================================================================= */
/* slide out to the left */
#keyframes slideOutLeft {
to { transform: translateX(-200%); }
}
#-moz-keyframes slideOutLeft {
to { -moz-transform: translateX(-200%); }
}
#-webkit-keyframes slideOutLeft {
to { -webkit-transform: translateX(-200%); }
}
/* slide in from the right */
#keyframes slideInRight {
from { transform:translateX(200%); }
to { transform: translateX(0); }
}
#-moz-keyframes slideInRight {
from { -moz-transform:translateX(200%); }
to { -moz-transform: translateX(0); }
}
#-webkit-keyframes slideInRight {
from { -webkit-transform:translateX(200%); }
to { -webkit-transform: translateX(0); }
}
EDIT - Controller:
angular.module('formApp')
.controller('formController', ['$scope', function($scope) {
$scope.beforeRender = function ($view, $dates, $leftDate, $upDate, $rightDate) {
var index = Math.floor(Math.random() * $dates.length);
$dates[index].selectable = false;
}
// we will store all of our form data in this object
$scope.formData = {};
$scope.formData.date = "";
$scope.opened = false;
$scope.time1 = new Date();
$scope.showMeridian = true;
//Datepicker
$scope.dateOptions = {
'year-format': "'yy'",
'show-weeks' : false,
'show-time':true
};
// function to process the form
$scope.processForm = function() {
alert('awesome!');
var appointment = new Appointment();
console.log(appointment);
};
}]);
The services come from the following plugin:
https://github.com/dalelotts/angular-bootstrap-datetimepicker
so would suspect it's not in there - but as I'm a noob i'm a little lost :-/
I found this to cause the issue:
You may be having the options setup in date picker. ie:
datepicker-options="dateOptions"
Now, try adding the options to your controller. ie:
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
If it helps - my HTML looked like this:
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="dd/MM/yyyy" ng-model="dt" is-open="status.opened"
min-date="minDate" max-date="'2020-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
Angular-Animate is a core library, and it's functionality is directly based on the core Angular library. It is critical that these libraries remain in sync. You must use the identical version for both libraries.

How to use a keypress event in AngularJS?

I want to catch the enter key press event on the textbox below. To make it more clear I am using a ng-repeat to populate the tbody. Here is the HTML:
<td><input type="number" id="closeqty{{$index}}" class="pagination-right closefield"
data-ng-model="closeqtymodel" data-ng-change="change($index)" required placeholder="{{item.closeMeasure}}" /></td>
This is my module:
angular.module('components', ['ngResource']);
I am using a resource to populate the table and my controller code is:
function Ajaxy($scope, $resource) {
//controller which has resource to populate the table
}
You need to add a directive, like this:
Javascript:
app.directive('myEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.myEnter);
});
event.preventDefault();
}
});
};
});
HTML:
<div ng-app="" ng-controller="MainCtrl">
<input type="text" my-enter="doSomething()">
</div>
An alternative is to use standard directive ng-keypress="myFunct($event)"
Then in your controller you can have:
...
$scope.myFunct = function(keyEvent) {
if (keyEvent.which === 13)
alert('I am an alert');
}
...
My simplest approach using just angular build-in directive:
ng-keypress, ng-keydown or ng-keyup.
Usually, we want add keyboard support for something that already handled by ng-click.
for instance:
<a ng-click="action()">action</a>
Now, let's add keyboard support.
trigger by enter key:
<a ng-click="action()"
ng-keydown="$event.keyCode === 13 && action()">action</a>
by space key:
<a ng-click="action()"
ng-keydown="$event.keyCode === 32 && action()">action</a>
by space or enter key:
<a ng-click="action()"
ng-keydown="($event.keyCode === 13 || $event.keyCode === 32) && action()">action</a>
if you are in modern browser
<a ng-click="action()"
ng-keydown="[13, 32].includes($event.keyCode) && action()">action</a>
More about keyCode:
keyCode is deprecated but well supported API, you could use $evevt.key in supported browser instead.
See more in https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
Another simple alternative:
<input ng-model="edItem" type="text"
ng-keypress="($event.which === 13)?foo(edItem):0"/>
And the ng-ui alternative:
<input ng-model="edItem" type="text" ui-keypress="{'enter':'foo(edItem)'}"/>
Here is what I figured out when I was building an app with a similar requirement,
it doesn't require writing a directive and it's relatively simple to tell what it does:
<input type="text" ng-keypress="($event.charCode==13)?myFunction():return" placeholder="Will Submit on Enter">
You can use ng-keydown
="myFunction($event)" as attribute.
<input ng-keydown="myFunction($event)" type="number">
myFunction(event) {
if(event.keyCode == 13) { // '13' is the key code for enter
// do what you want to do when 'enter' is pressed :)
}
}
html
<textarea id="messageTxt"
rows="5"
placeholder="Escriba su mensaje"
ng-keypress="keyPressed($event)"
ng-model="smsData.mensaje">
</textarea>
controller.js
$scope.keyPressed = function (keyEvent) {
if (keyEvent.keyCode == 13) {
alert('presiono enter');
console.log('presiono enter');
}
};
You can also apply it to a controller on a parent element. This example can be used to highlight a row in a table by pressing up/down arrow keys.
app.controller('tableCtrl', [ '$scope', '$element', function($scope, $element) {
$scope.index = 0; // row index
$scope.data = []; // array of items
$scope.keypress = function(offset) {
console.log('keypress', offset);
var i = $scope.index + offset;
if (i < 0) { i = $scope.data.length - 1; }
if (i >= $scope.data.length) { i = 0; }
};
$element.bind("keydown keypress", function (event) {
console.log('keypress', event, event.which);
if(event.which === 38) { // up
$scope.keypress(-1);
} else if (event.which === 40) { // down
$scope.keypress(1);
} else {
return;
}
event.preventDefault();
});
}]);
<table class="table table-striped" ng-controller="tableCtrl">
<thead>
<tr>
<th ng-repeat="(key, value) in data[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in data track by $index" ng-click="draw($index)" ng-class="$index == index ? 'info' : ''">
<td ng-repeat="(key, value) in row">{{value}}</td>
</tr>
</tbody>
</table>
Trying
ng-keypress="console.log($event)"
ng-keypress="alert(123)"
did nothing for me.
Strangley the sample at https://docs.angularjs.org/api/ng/directive/ngKeypress, which does ng-keypress="count = count + 1", works.
I found an alternate solution, which has pressing Enter invoke the button's ng-click.
<input ng-model="..." onkeypress="if (event.which==13) document.getElementById('button').click()"/>
<button id="button" ng-click="doSomething()">Done</button>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Informe your name:<input type="text" ng-model="pergunta" ng-keypress="pressionou_enter($event)" ></input>
<button ng-click="chamar()">submit</button>
<h1>{{resposta}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
//create a service mitsuplik
app.service('mitsuplik', function() {
this.myFunc = function (parametro) {
var tmp = "";
for (var x=0;x<parametro.length;x++)
{
tmp = parametro.substring(x,x+1) + tmp;
}
return tmp;
}
});
//Calling our service
app.controller('myCtrl', function($scope, mitsuplik) {
$scope.chamar = function() {
$scope.resposta = mitsuplik.myFunc($scope.pergunta);
};
//if mitsuplik press [ENTER], execute too
$scope.pressionou_enter = function(keyEvent) {
if (keyEvent.which === 13)
{
$scope.chamar();
}
}
});
</script>
</body>
</html>
This is an extension on the answer from EpokK.
I had the same problem of having to call a scope function when enter is pushed on an input field. However I also wanted to pass the value of the input field to the function specified. This is my solution:
app.directive('ltaEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
// Create closure with proper command
var fn = function(command) {
var cmd = command;
return function() {
scope.$eval(cmd);
};
}(attrs.ltaEnter.replace('()', '("'+ event.target.value +'")' ));
// Apply function
scope.$apply(fn);
event.preventDefault();
}
});
};
});
The use in HTML is as follows:
<input type="text" name="itemname" lta-enter="add()" placeholder="Add item"/>
Kudos to EpokK for his answer.
What about this?:
<form ng-submit="chat.sendMessage()">
<input type="text" />
<button type="submit">
</form>
Now when you push enter key after write something in your input, the form know how to handle it.
Some example of code that I did for my project.
Basically you add tags to your entity.
Imagine you have input text, on entering Tag name you get drop-down menu with preloaded tags to choose from, you navigate with arrows and select with Enter:
HTML + AngularJS v1.2.0-rc.3
<div>
<form ng-submit="addTag(newTag)">
<input id="newTag" ng-model="newTag" type="text" class="form-control" placeholder="Enter new tag"
style="padding-left: 10px; width: 700px; height: 33px; margin-top: 10px; margin-bottom: 3px;" autofocus
data-toggle="dropdown"
ng-change="preloadTags()"
ng-keydown="navigateTags($event)">
<div ng-show="preloadedTags.length > 0">
<nav class="dropdown">
<div class="dropdown-menu preloadedTagPanel">
<div ng-repeat="preloadedTag in preloadedTags"
class="preloadedTagItemPanel"
ng-class="preloadedTag.activeTag ? 'preloadedTagItemPanelActive' : '' "
ng-click="selectTag(preloadedTag)"
tabindex="{{ $index }}">
<a class="preloadedTagItem"
ng-class="preloadedTag.activeTag ? 'preloadedTagItemActive' : '' "
ng-click="selectTag(preloadedTag)">{{ preloadedTag.label }}</a>
</div>
</div>
</nav>
</div>
</form>
</div>
Controller.js
$scope.preloadTags = function () {
var newTag = $scope.newTag;
if (newTag && newTag.trim()) {
newTag = newTag.trim().toLowerCase();
$http(
{
method: 'GET',
url: 'api/tag/gettags',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
params: {'term': newTag}
}
)
.success(function (result) {
$scope.preloadedTags = result;
$scope.preloadedTagsIndex = -1;
}
)
.error(function (data, status, headers, config) {
}
);
} else {
$scope.preloadedTags = {};
$scope.preloadedTagsIndex = -1;
}
};
function checkIndex(index) {
if (index > $scope.preloadedTags.length - 1) {
return 0;
}
if (index < 0) {
return $scope.preloadedTags.length - 1;
}
return index;
}
function removeAllActiveTags() {
for (var x = 0; x < $scope.preloadedTags.length; x++) {
if ($scope.preloadedTags[x].activeTag) {
$scope.preloadedTags[x].activeTag = false;
}
}
}
$scope.navigateTags = function ($event) {
if (!$scope.newTag || $scope.preloadedTags.length == 0) {
return;
}
if ($event.keyCode == 40) { // down
removeAllActiveTags();
$scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex + 1);
$scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
} else if ($event.keyCode == 38) { // up
removeAllActiveTags();
$scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex - 1);
$scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
} else if ($event.keyCode == 13) { // enter
removeAllActiveTags();
$scope.selectTag($scope.preloadedTags[$scope.preloadedTagsIndex]);
}
};
$scope.selectTag = function (preloadedTag) {
$scope.addTag(preloadedTag.label);
};
CSS + Bootstrap v2.3.2
.preloadedTagPanel {
background-color: #FFFFFF;
display: block;
min-width: 250px;
max-width: 700px;
border: 1px solid #666666;
padding-top: 0;
border-radius: 0;
}
.preloadedTagItemPanel {
background-color: #FFFFFF;
border-bottom: 1px solid #666666;
cursor: pointer;
}
.preloadedTagItemPanel:hover {
background-color: #666666;
}
.preloadedTagItemPanelActive {
background-color: #666666;
}
.preloadedTagItem {
display: inline-block;
text-decoration: none;
margin-left: 5px;
margin-right: 5px;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 20px;
padding-right: 10px;
color: #666666 !important;
font-size: 11px;
}
.preloadedTagItem:hover {
background-color: #666666;
}
.preloadedTagItemActive {
background-color: #666666;
color: #FFFFFF !important;
}
.dropdown .preloadedTagItemPanel:last-child {
border-bottom: 0;
}
I'm a bit late .. but i found a simpler solution using auto-focus .. This could be useful for buttons or other when popping a dialog :
<button auto-focus ng-click="func()">ok</button>
That should be fine if you want to press the button onSpace or Enter clicks .
here's my directive:
mainApp.directive('number', function () {
return {
link: function (scope, el, attr) {
el.bind("keydown keypress", function (event) {
//ignore all characters that are not numbers, except backspace, delete, left arrow and right arrow
if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39) {
event.preventDefault();
}
});
}
};
});
usage:
<input number />
you can use ng-keydown , ng-keyup , ng-press such as this .
to triger a function :
<input type="text" ng-keypress="function()"/>
or if you have one condion such as when he press escape (27 is the key
code for escape)
<form ng-keydown=" event.which=== 27?cancelSplit():0">
....
</form>
I think using document.bind is a bit more elegant
constructor($scope, $document) {
var that = this;
$document.bind("keydown", function(event) {
$scope.$apply(function(){
that.handleKeyDown(event);
});
});
}
To get document to the controller constructor:
controller: ['$scope', '$document', MyCtrl]
(function(angular) {
'use strict';
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
element.bind("keydown keypress", function (event) {
console.log('keydown keypress', event.which);
if(event.which === 13) {
event.preventDefault();
}
});
}
};
}]);
})(window.angular);
All you need to do to get the event is the following:
console.log(angular.element(event.which));
A directive can do it, but that is not how you do it.

Resources