Fire a method when click an Enter key - angularjs

<form novalidate name="frm1" autocomplete="off">
//UI elements
<div class="col-sm-3 col-sm-offset-6">
<button ng-click="MyFunc()">Next Step</button>
</div>
</form>
Can you tell me how to fire MyFunc() method when click the enter key.On the above form where there is no submit button. Thanks in advance.

Try this:
<input ng-keyup="$event.keyCode == 13 ? MyFunc() : null" >
At form level you can use this:
<form ng-submit="myFunc()" ...>

I have written below mentioned directive and it works.
Directive :
angular.module('app.directives')
.directive('ngEnter', function () { //a directive to 'enter key press' in elements with the "ng-enter" attribute
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
})
HTML
<form novalidate name="frm1" autocomplete="off">
//UI elements
<input name="userName" type="text" ng-enter="MyFunc()"/>
<div class="col-sm-3 col-sm-offset-6">
<button ng-click="MyFunc()">Next Step</button>
</div>
</form>

Simply write (keyup.enter)="your_function_name()" in your html file in same way you write (click).
Below is a code snippet.
<input type="text" [(ngModel)]="modelSearchedData" (keyup.enter)="getModelList()">

What you should do is binding your function on submit event instead of enter key. You should not focus on enter, because for exemple on the iPhone there is a keyboard button to execute form, which behave like enter but is not enter event ... and the iPhone is just one exemple :D
So you should change your <button> by an input <type="submit"/>
This way enter key will automatically fire the form submit event.
Then in your submit event, return false; to prevent HTML action (which send the form) and execute your code.
HTML
<form novalidate name="frm1" autocomplete="off">
//UI elements
<div class="col-sm-3 col-sm-offset-6">
<input type="submit" value="Next Step" />
</div>
</form>
JS
$('form').submit(function () {
MyFunc();
return false;
});
I hope this answer your question.
PS : you can use ng-submit instead of jQuery selector, if you do not want to use jQuery.

I found a solution that does not require a directive. I was already using ng-change to capture each keypress and perform a search, but clicking Enter would throw my SharePoint page into Edit mode. SharePoint doesn't let you access the form tag, so most of these solutions didn't work for me.
This solution was much simpler and kept my code in the same place, I have an ng-change AND an ng-keypress event that point to the same event handler, vm.txtSearchChange():
HTML
<input id="txtSearch" type="text" style="width: 400px;" ng-change="vm.txtSearchChange()"
ng-keypress="$event.keyCode == 13 ? vm.txtSearchChange($event) : null"
ng-model="vm.Search" ng-model-options="{debounce: 200}"/>
Note the ng-change event does not pass the $event attribute, and handles the legitimate key presses, while the ng-keypress event is only for the enter key.
SCRIPT
vm.txtSearchChange = function ($event) {
if ($event) {
$event.preventDefault();
return;
}
console.log("Search: " + vm.Search);
vm.showResults();
} // end vm.txtSearchChange
When $event is not null, it's the enter key, we call preventDefault() and don't process further. When $event is null, it's a valid key, and we pass it along to vm.showResults() for processing.

Most of the answers here involve additional workarounds that simply are not needed, you can work with the standard form submission by making these two small changes and the Enter key will function as desired.
Move the ng-click from the button to the form, and make it an ng-submit
Add a type="submit" to the button
For more complex forms with multiple buttons you might need to try some of the workarounds, but for the majority of cases this will work.
<form novalidate name="frm1" autocomplete="off" ng-submit="MyFunc()">
//UI elements
<div class="col-sm-3 col-sm-offset-6">
<button type="submit">Next Step</button>
</div>
</form>

<input type="text" name="Inputvalue" id="Inputvalue" ng-change="EnableDisableCheckButton()" ng-model="enteredInputValue" ng-disabled="isDisabledInputvalueTextbox" ng-blur="" data-ng-keypress="onEnterKeyPress($event)" />
<button type="button" class="btn btn-primary" ng-disabled="isDisabledCheckButton" ng-click="ValidateInputvalue()">Check</button>
And in your JavaScript file, add below:
$scope.onEnterKeyPress = function (event) {
if (event.charCode == 13) //if enter is hot then call ValidateInputvalue().
$scope.ValidateInputvalue();
}

This example worked for me:
HTML Code:
<input matInput type="text" [(ngModel)]="searchString" ng-change="startSearch()" ng-keypress="$event.keyCode == 13 ? startSearch($event) : null">
Typescript:
#HostListener('document:keypress', ['$event'])
startSearch(event: KeyboardEvent) {
if (event.code === "Enter") {
//Code that you need to run
}
}
https://go.tiny.cloud/blog/angular-5-tutorial-step-step-guide-first-angular-5-app/

Related

Error message does not hide after angular form validation

This is my form my HTML
<form id = "myform" name="myform" ng-submit="saveForm()" novalidate >
<div class="input-group">
<span class="input-group-addon"> <img src="/icon.png" alt=""/> </span>
<input type="text" class="form-control" id="username" name="username" ng-model="username" placeholder="Username" autofocus required>
</div>
<span ng-show="formInvalid">Please enter username</span>
<button type="submit" class="btn btn-default" id="saveBtn"> Save </button>
</form>
And inside the controller I have
$scope.formInvalid = false;
$scope.saveForm = function(){
if($scope.myform.username.$invalid){
$scope.formInvalid = true;
}
if($scope.myform.$valid){
//....save it....
At first the form has no error message, if I hit "Save" the "Please enter username" appears, so far, all good.
But if I click on the form field to type a username, the error message does not go away. Even if I finish typing and click somewhere else, the error message still does not go away.
I also try
if(!$scope.myform.username.$valid){
$scope.formInvalid = true;
}
and I also try together
if(!$scope.myform.username.$valid){
$scope.formInvalid = true;
}
if($scope.myform.username.$valid){
$scope.formInvalid = false;
}
and the problem is still there. How can I debug? How do I fix this?
Thanks
You don't have to introduce and maintain a new variable ($scope.formInvalid) for managing the state of your form. Angular maintains the valid / invalid state of the form for you.
As your form is named myform, just show the message about the username based on the value of myform.username.$invalid, and save the form only if myform.$valid is true:
HTML
<span ng-show="myform.username.$invalid">Please enter username</span>
JS
$scope.saveForm = function () {
if ($scope.myform.$valid) {
// save the form
}
};
See fiddle
you can try a watch event,
$scope.$watch('myform.$valid', function(n, o) {
if(n) {
$scope.formInvalid = false;
} else {
$scope.formInvalid = true;
}
});
But i might even be a better idea, if you start using validators.
you do not trigger a change to form invalid property anywhere, I suggest you solve this issue with angulars built in validators and ng-messages module, which will listen to changes on you're form inputs and notify when the inputs are valid or invalid and notify the warning text.
Another approach you can take is use the ng-change directive on the inputs you want to listen to changes in and trigger and update on the form invalid property according to the inputs validity.
example : (taken from the official angular website )
<form name="myForm">
<label>
Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="5"
ng-maxlength="20"
required />
</label>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
</form>
i think this is the most elegant way to do it.

angular JS dynamic tooltip creation

EDIT:
It seems like the Error or wrong handling is because the scope does not gets updated when the email field is not valid... is there a way to chang that?
this is my first question on stackoverflow so i hope i will do it right.
I am pretty new to angular js and i am creating some basics at the moment.
in my demo app i created a normal form in a bootstrap style and i was planing to create a directive to show the errors in a bootstrap way. so far so good. that was working and my next step was to create a angular js bootstrap tooltip directive when the form is not valid. the thing is, that i wanna do this dynamic.
i post some code to explain it better:
<b>HTML:</b>
<div class="container" ng-controller="LoginCtrl as vm">
<form id="login" name="vm.loginForm" class="form-signin" ng-submit="vm.login()" novalidate>
<div show-errors>
<input type="email" name="username" ng-model="vm.credentials.username" class="form-control" placeholder="Email address" required autofocus>
</div>
<div show-errors>
<input type="password" name="password" ng-model="vm.credentials.password" class="form-control" placeholder="Password" required>
</div>
<button class="btn btn-lg btn-primary btn-block" id="submit" type="submit">
Login
<span class="spinner"><i class="fa fa-refresh fa-spin"></i></span>
</button>
</form>
</div>
<b>showError Directive:</b>
(function () {
angular.module('testapp.Validate', []).directive('showErrors', validationDirective);
/**
* #name validate directive
*/
function validationDirective($compile) {
return {
require: '^form',
restrict: 'A',
link: function (scope, el, attrs, formCtrl) {
var inputNgEl = angular.element(el[0].querySelector("[name]"));
var inputName = inputNgEl.attr('name');
inputNgEl.bind('blur', function () {
toogle(inputNgEl, el, formCtrl[inputName]);
});
scope.$on('show-errors-check', function () {
toogle(inputNgEl, el, formCtrl[inputName]);
});
}
}
}
function toogle(inputNgEl, fromGroup, inputField) {
fromGroup.toggleClass('has-feedback has-error', inputField.$invalid);
if (inputField.$invalid && !fromGroup[0].querySelector(".glyphicon-remove")) {
inputNgEl.after('<span class="glyphicon form-control-feedback glyphicon-remove"></span>');
} else if (!inputField.$invalid) {
if (fromGroup[0].querySelector(".glyphicon-remove") != null) {
fromGroup[0].querySelector(".glyphicon-remove").remove();
}
}
}
})();
That is working so far . it just adds a has-feedback,has-error class to the parent div and a span with an error-icon after the input.
but back to my plan, now I also want to create a dynamic tooltip for the input. so I planed to add something like that in the "toogle" function
inputNgEl.attr('uib-tooltip',"aaaa");
inputNgEl.attr('tooltip-placement',"right");
inputNgEl.attr('tooltip-trigger',"mouseenter");
inputNgEl.attr('tooltip-class',"testTool");
But that is not working because the input field got already compiled before.
so I asked google about it and there I found some solutions with $compile
$compile(inputNgEl)(scope);
But when I am using it, and I type in a valid email address the field gets reset. aaa#aaa (still working) but after I add the aaa#aaa. (the field gets reseted - I guess compiled again). the tooltip would work btw.
Can anybody help me with that or is there a better solution to create a dynamic angular bootstrap tooltip?
Maybe you need to add a $watch on the input element, and see if it changes, add a tooltip in the input element and compile it

AngularJS how to disable button after click

Hi I have a form with some inputs like email, title, color...
I have 2 buttons "Save" and "Undo changes".
I need that this buttons will be always disabled accept, if something was changed.
For example I started to change email and then I considered. While I'm typing new email buttons should be enabled, but after click on one of them they should be disabled again.
<form name="form" ng-submit="change()" novalidate>
<input type="text" ng-model="title"/>
<input type="email" name="email" ng-model="email" placeholder="{{email}}" />
<input type="color" ng-model="color"/>
<button type="submit" ng-disabled="!form.$dirty">SAVE</button>
<a ng-click="cancel()" ng-disabled="!form.$dirty">UNDO CHANGES</a>
</form>
How can I make them disable again after click on one of buttons?
Call $scope.form.$setPristine() to cancel all the dirty flags:
function TodoCtrl($scope) {
$scope.change = function() {
$scope.form.$setPristine();
}
$scope.cancel = function() {
$scope.form.$setPristine();
}
}
Example: http://jsfiddle.net/ej5et0f5/1/
Simply create a flag variable that you'll set to true after submitting and to false after changing inputs, then just do:
<button type="submit" ng-disabled="flagVariable">

Call the first <span> in a scrollbar when press enter using angularjs

I have a text box which is using for search.When enter the characters it searches the values and shows one by one in a scrollbar. When i click on any found value it redirects to the related page but when press enter it should call first value in that scrollbar.Below is my code.
<div><input type="text" value="" placeholder="search" ng-model="searchText" name="testName" ng-keyup="search()"></div>
<div class="scroll" ng-show="searchText.length" ng-hide="!searchText.length">
<div ng-repeat="relatedData in data">
<span ng-click="showDetails(relatedData)" ng-model="searchText">{{ relatedData }} </span><br />
</div>
</div>
and below is my script code:
$scope.showDetails = function(relatedData) {
$http.get("searchInfo.json").success(function(response) {
var searchT = relatedData;
$http.get(searchT+'Details.json').success(function(response) {
$scope.details = response;
$scope.searchText = "";
});
});
}
Could you please help to call first value in multiple values scrollbar,Thanks.
One way would be to wrap your search field in a form element:
<form ng-submit="showDetails(data[0])">
<input type="text"
value=""
placeholder="search"
ng-model="searchText"
name="testName"
ng-keyup="search()">
</form>
ng-submit will catch the form submit event triggered by pressing Enter.

AngularJS: Required form field not woking with ng-click submit

<div ng-app>
<div ng-controller="Ctrl">
<form ng-submit="submit() ">
<textarea ng-model="text" required></textarea>
<div ng-click="submit()" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</div>
<button type="submit" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</button>
</form>
{{list}}
</div>
</div>
I want to submit an Angular form with a custom div button but when I do it like above, the "required" statements are not taken into account like it is done for the button.
When the textarea is empty the first button runs the submit() function anyway.
Is it possible to have the same behavior as the button ?
Here is a JsFiddle illustrating this:
http://jsfiddle.net/xKkvj/55/
I think you should be using an input rather than a div, eg:
<input type="submit" ng-click="submit()" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</input>
I've tested it on your jsFiddle, and it works fine.
If you really must use a <div>, use it to wrap the <input>
UPDATE
It looks like you can't use anything other than an input or a button as that is what ngForm listens to for form submission. You could either extend ngForm or you could use a hidden button and trigger that from your div like so:
<div onClick="document.getElementById('hiddenButton').click();" style="background-color:#0000ff;cursor:pointer;width:100px;">Create !</div>
<button id='hiddenButton' type="submit" style="display:none;">Create !</button>
jsFiddle here. Hopefully this'll do the trick for you.
If you want to submit form from a div element, then you should manually test if form is valid in your submit handler:
function sumbit() {
if (form.$invalid) {
return;
}
// Other code...
}
The point is that when you submit your form via <input type="submit"/>, then form validation check is performed internally & form handler do not invoked in case of invalid form.
UPDATE
Your jsfiddle form handler should look like:
$scope.submit = function () {
if ($scope.submitCreateSurveyForm.$invalid) {
return;
}
if ($scope.text) {
$scope.list.push($scope.text);
$scope.text = '';
}
console.log("sent");
};

Resources