How to use a keypress event in AngularJS? - 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.

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>

Resetting Form When modalpop up gets closed if i click any place in my page

I am using Angular 1.3.I have a form in modal Pop-up.After submitting the form my modal Pop-up form is reset and if i click cancel button my form also reset
$scope.add_user = function(add_form)
{
if(add_form.$valid)
{
$http({
method:'POST',
url:file_path,
headers:{'Content_Type':'appliaction/json'},
data:$scope.text
}).success(function(data){
$scope.modalShown_add = ! $scope.modalShown_add;
$scope.modalShown_addsuccess = !$scope.modalShown_addsuccess;
$scope.getlist();
add_form.reset();
}).error(function(data){
add_form.reset();
})
}
}
but when i have any validation error if i click any place of my page my modal Pop-up gets closed after i open the modal Pop-up i am not able to reset my form.Suppose if i pass form name in add function to reset the form i am getting error
$scope.add =function()
{
$scope.modalShown_add = ! $scope.modalShown_add;
}
Each form directive creates an instance of FormController so you can access it by setting the name property like name="$ctrl.addForm".
To clear the form you need to clear the model and then use form controller to control the validation state of your form (see resetForm method):
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
var ctrl = this;
ctrl.users = [];
ctrl.showPopup = false;
ctrl.openModal = openModal;
ctrl.saveUser = saveUser;
function openModal(user) {
ctrl.showPopup = true;
ctrl.user = angular.copy(user); // a copy of the user to disable 2-way binding with the list
resetForm(ctrl.addForm);
}
function resetForm(form){
form.$setPristine(); //set the form to its pristine state
form.$setUntouched(); //set the form to its untouched state
}
function saveUser(user){
//your saving logic here it is just a sample
if (!user.id){
user.id = ctrl.users.length;
ctrl.users.push(user);
} else {
ctrl.users[user.id] = user;
}
//hide pop up
ctrl.showPopup = false;
}
$scope.$ctrl = ctrl;
}])
.directive('modalDialog', function() {
return {
restrict: 'E',
scope: {
show: '='
},
replace: true,
transclude: true,
link: function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
if (attrs.overflow)
scope.dialogStyle.overflow = attrs.overflow;
scope.hideModal = function() {
scope.show = false;
};
},
template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'><i class='fa fa-times-circle'></i></div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"// See below
};
});
.ng-invalid.ng-touched {
border: 1px solid red;
}
.ng-modal{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.ng-modal-overlay{
background-color: black;
opacity: 0.3;
z-index: 0;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.ng-modal-dialog {
position: relative;
top: 50%;
z-index: 1;
background-color: white;
padding: 1em;
border: 1px solid gray;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.3.20/angular.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<!-- send en empty object to create a new user -->
<button ng-click="$ctrl.openModal({})">Show</button>
<div>
{{u.name}}<span ng-repeat-end ng-if="!$last">, </span>
</div>
<modal-dialog show="$ctrl.showPopup">
<form name="$ctrl.addForm" ng-submit="$ctrl.saveUser($ctrl.user)">
<input name="user_name" ng-model="$ctrl.user.name" type="text" ng-required="true"/>
<div>
<button type="submit">Save</button>
<button type="button" ng-click="$ctrl.showPopup = false;">Cancel</button>
</div>
</form>
</modal-dialog>
</div>
</div>
Hope this helps you.

AngularJS with CSS3 Animations - Slideshow Issues

I am attempting to create a simple content slider with AngularJS. I am following this tutorial:https://www.sitepoint.com/creating-slide-show-plugin-angularjs/
However, the content is "jumping". The next slide appears below the current one; it does not appear in its appropriate place while the other is fading out. Here is an image that hopefully clarifies the issue:
The HTML:
<div class="row" id='topSlider' ng-controller="SliderCtrl">
<h2 class="col-sm-12">Latest Stories</h2>
<div class="col-sm-12">
<div class="slider" ng-repeat="story in stories" ng-show="story.visible">
<a class="containerLink" href="View/ViewPost?postID={{story.StoryID}}">
<div class="slide">
<h3 class="cursive">{{story.Title}}</h3>
<blockquote>{{story.StoryPara}}</blockquote>
</div>
</a>
</div>
</div>
<div class="row" id="arrows">
<span class="glyphicon glyphicon-arrow-left"></span>
<span class="glyphicon glyphicon-arrow-right"></span>
</div>
The controller:
app.controller("SliderCtrl", ["$scope", "$http", "$timeout", function ($scope, $http, $timeout) {
$scope.currentIndex = 0;
$http.post("/StoryWall/Home/GetLatestStories").then(function (response) {
$scope.stories = response.data;
$scope.stories[0].visible = true;
},
function (response) {
$scope.stories = response.data;
});
$scope.next = function () {
$scope.currentIndex < $scope.stories.length - 1 ? $scope.currentIndex++ : $scope.currentIndex = 0;
};
$scope.prev = function () {
$scope.currentIndex > 0 ? $scope.currentIndex-- : $scope.currentIndex = $scope.stories.length - 1;
};
$scope.$watch("currentIndex", function () {
$scope.stories.forEach(function (story) {
story.visible = false;
});
$scope.stories[$scope.currentIndex].visible = true;
});
var timer;
var sliderFunction = function () {
timer = $timeout(function () {
$scope.next();
timer = $timeout(sliderFunction, 2000);
}, 5000);
};
sliderFunction();
}]);
and the CSS:
.slider.ng-hide-add, .slider.ng-hide-remove {
-webkit-transition:all linear 1s;
-moz-transition:all linear 1s;
-o-transition:all linear 1s;
transition:all linear 1s;
display:block!important;
clear: none;
float: none;
}
.slider.ng-hide-add.ng-hide-add-active,
.slider.ng-hide-remove {
opacity: 0;
}
.slider.ng-hide-add,
.slider.ng-hide-remove.ng-hide-remove-active {
opacity: 1;
}
Please note, if I remove the CSS it works just fine. The containers hide and show as they should. However, I would like to be able to apply some animations. I am new to both CSS animations and AngularJS; I apologize if this is a redudant or obvious issue.
check this css -> https://daneden.github.io/animate.css/
it's my script
var app=angular.module("app",[]);
app.controller("control",function($scope){
$scope.tab="1";
});
you focus on ng-show method
for example
all slider item in div like that
<div ng-show="tab==1" class="slider-item animated slideInRight">
...............
</div>
and your button must be
<button ng-mouseover="tab=1">1</button>
I hope I could help you

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.

Open ui.boostrap typeahead dropdown up

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.

Resources