HTML:
<html ng-app="app">
<div class="container" style="margin-top: 30px">
<input type="text" ng-model="newName" key-filter/>
<input type="text" ng-model="newName" key-filter/>
<input type="text" ng-model="newName" key-filter/>
<input type="text" ng-model="newName" key-filter/>
</div>
</html>
JS:
var app = angular.module('app', []);
app.directive('keyFilter', function() {
var pattern = /([\s !$%^&*()_+|~=`{}\[\]:";'<>?,.\/])/;
function link(scope) {
scope.$watch('model', function() {
if(scope.model === undefined)
return
if(pattern.test(scope.model)) {
scope.model = scope.model.replace(pattern, '');
Materialize.toast('Denied symbol', 4000, 'rounded');
}
});
}
return {
restrict: 'A',
scope: {
model: '=ngModel'
},
link: link
}
});
I have many inputs which are bind to the same model, and I am filtering user input, when user press a denied key I wanted to show a toast to inform him that he can't use this symbol, but the count of toasts is equal to the count of inputs bind to the same model.
I thought i'm working only with model which is one.
Example here:
http://codepen.io/anon/pen/XbLjVY?editors=101
How can I fix that, or change the logic how it works
p.s. angular beginner
If they are all bind to the same model every change in one is send to the others, so just put your directive on one input not all of them.
Here is a working plunkr :
http://plnkr.co/edit/dI5TMHms2wsPHc9Xqewf?p=preview
using :
<input type="text" ng-model="newName" key-filter/>
<input type="text" ng-model="newName" />
<input type="text" ng-model="newName" />
<input type="text" ng-model="newName" />
You can see in the console the message being displayed only once and from any input field
Related
This is a typical example of the use of ng-messages in AngularJS (1.x):
<form name="demoForm">
<input name="amount" type="number" ng-model="amount" max="100" required>
<div ng-messages="demoForm.amount.$error">
<div ng-message="required">This field is required</div>
</div>
<button type="submit">test submit</button>
</form>
see: http://jsfiddle.net/11en8swy/3/
I now want to change this example so the "This field is required" error only shows when the field is touched ($touched) or the user hits the submit button.
I cannot use the ng-submitted class on the form since the validation error prevents the submitting of the form.
How should I do this?
Thanks
You can do this using ng-show:
<div ng-messages="demoForm.amount.$error" ng-show="demoForm.amount.$touched">
<div ng-message="required">This field is required</div>
</div>
And use a custom directive. See a working demo:
var app = angular.module('app', ['ngMessages']);
app.controller('mainCtrl', function($scope) {
});
app.directive('hasFocus', function($timeout) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
element.on('focus', function() {
$timeout(function() {
ctrl.hasFocusFoo = true;
})
});
element.on('blur', function() {
$timeout(function() {
ctrl.hasFocusFoo = false;
})
});
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-messages.js"></script>
<body ng-app="app" ng-controller="mainCtrl">
<form name="demoForm">
<input name="amount" type="number" ng-model="amount" max="100" required has-focus>
<div ng-messages="demoForm.amount.$error" ng-show="demoForm.amount.$touched || demoForm.amount.hasFocusFoo">
<div ng-message="required">This field is required</div>
</div>
<button type="submit">test submit</button>
</form>
</body>
The directive is basically setting another hasFocusFoo field on the ngModel controller then we can easily use that directive.
Ah, at the PC at last.
https://plnkr.co/edit/EX3UmoAOKmTKlameBXRa?p=preview
<form name="mc.form">
<input type="text" name="empty" ng-model="mc.empty" required />
<label ng-show="mc.form.empty.$dirty && mc.form.empty.$error.required">i'm empty</label>
</form>
MainController.$inject = ['$timeout'];
function MainController($timeout) {
var vm = this;
$timeout(function(){
vm.form.$setPristine();
});
vm.submit = function(){
if(vm.form.$valid){
alert('yay');
}else{
(vm.form.$error.required || []).forEach(function(f){
f.$dirty = true;
});
}
}
}
Here is how I handle this task in my solution. form.$setPristine() - sets the field in a pristine state, so field isn't $dirty and error hidden. But after submit I manually state required fields in a $dirty state, so errors become visible. + if you type something, and delete it after, the error would be visible without submitting a form.
I'm creating a form with Angular and Angular Messages. This form lies in a template that gets brought into the view with Angular Route. When I first load the form, everything functions properly. Then, when I load a different view and switch back to the form's view, I'm unable to focus on the text inputs. What's happening?
The HTML
<form name='submission' ng-submit='submit()'>
<label class='text-input-group' for='name'>
<div class='label'>Name</div>
<input id='name' name='name' ng-model='submissionName' type='text' required>
<div ng-messages='submission.name.$error' ng-if='submission.name.$touched'>
<div ng-message='required'>* Please enter your name</div>
</div>
</label>
<label class='text-input-group' for='email'>
<div class='label'>Email</div>
<input id='email' name='email' ng-model='submissionEmail' type='email' required>
<div ng-messages='submission.email.$error' ng-if='submission.email.$touched'>
<div ng-message='required'>* Please enter your email address</div>
<div ng-message='email'>* Please enter a valid email address</div>
</div>
</label>
<label class='text-input-group' for='message'>
<div class='label'>Message</div>
<textarea id='message' name='message' ng-model='submissionMessage' ng-maxlength='2000' maxlength='2000' required></textarea>
<div ng-messages='submission.message.$error' ng-if='submission.message.$touched'>
<div ng-message='required'>* No message?</div>
<div ng-message='maxlength'>* Your message unfortunately can't exceed 20,000 characters</div>
</div>
</label>
<label class='checkbox-input-group' for='send-user-a-copy'>
<div class='label'>Send me a copy</div>
<input id='send-user-a-copy' name='sendUserACopy' ng-init='submissionSendUserACopy = false;' ng-model='submissionSendUserACopy' type='checkbox'>
</label>
<button type='submit'>Button</button>
</form>
The JavaScript
var contact = angular.module('app.contact', ['ngRoute']);
contact.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/contact', {
templateUrl: 'partials/contact.html',
controller: 'ContactController'
});
}]);
contact.controller('ContactController', ['$scope', function($scope) {
$scope.reset = function() {
$scope.submissionName = '';
$scope.submissionEmail = '';
$scope.submissionMessage = '';
$scope.submissionSendUserACopy = '';
$scope.submission.$setPristine();
}
$scope.$on('$routeChangeSuccess', function() {
console.log($scope.submission);
$scope.reset();
});
$scope.submit = function() {
if($scope.submission.$valid) {
console.log({
'name' : $scope.submissionName,
'email' : $scope.submissionEmail,
'message' : $scope.submissionMessage,
'sendUserACopy' : $scope.submissionSendUserACopy
});
}
}
}]);
Any answers / suggestions would be greatly appreciated. Thank you!
I wrote this to solve the issue with focus not applying on route changes in Angular.
import { Directive, ElementRef, AfterContentInit } from '#angular/core';
#Directive({
selector: '[focusOnInit]'
})
export class FocusDirective implements AfterContentInit {
constructor(public el: ElementRef) {}
ngAfterContentInit() {
this.el.nativeElement.focus();
}
}
usage
<input type="text" focusOnInit>
There is an attribute autofocus introduced in HTML5. I would suggest you adding that attribute in the first input element.
<input type="text" ng-model="firstName" autofocus />
But that has a limitation too!! Currently, browsers only focus on the input element directive on page load. So you will fall into the same problem that you are currently facing. So you can simply add an Angular directive with the same name i.e. autofocus which will programmatically focus the element as that directive is executed when the same view is loaded again.
myApp.directive('autofocus', [function() {
return {
restrict: 'A',
link: function(scope, element) {
element[0].focus();
}
};
}]);
(This is the format in Angular 1, please write it in Angular 2 if you are using Angular 2.)
Since even the same view has been loaded before, Angular will execute all the directives when the view is loaded again, this directive will focus the element after you switch back from another view.
<input type="text" ng-model="user.username" name="username" required>
<div class="sidetip">
<div ng-show="signup.username.$pristine">
<span>Choose a Username.</span>
</div>
I only want to show the "Choose a Username", If the form is pristine AND the input "username" is focused. How can I accomplish that?
The ng-focus seems like I only can apply on the input, and not what I am asking for "When the Input username is active, display this is if form username also is pristine"...
Something like this would work?
Here is a demo
<form name='signup' ng-submit="submit()" ng-controller="Ctrl">
Username:
<input type="text" ng-model="user.username" name="username" ng-focus="usernameIsFocus=true" ng-blur="usernameIsFocus=false" required />
<div class="sidetip">
<div ng-show="signup.username.$pristine && usernameIsFocus">
<span>Choose a Username. Click outside text field to hide this tip.</span>
</div>
</div>
</form>
just a side note
signup.username.$pristine
is not the same as
user.username == ''
so if you enter text in input username and then delete it, the first will be false and the second will be true
Angular 1.2 has ngBlur and ngFocus directives, in older versions you can create a directive which changes value given variable on focus is-focus="usernameIsFocus"
<input type="text" ng-model="user.username" name="username" required is-focus="usernameIsFocus">
<div class="sidetip">
<div ng-show="usernameIsFocus">
<span>Choose a Username.</span>
</div>
</div>
directive
app.directive('isFocus', function(){
return {
scope: {
isFocus: '='
},
link: function(scope, element, attrs){
element.on('focus', function() {
scope.$apply(function () {
scope.isFocus = true;
});
});
element.on('blur', function() {
scope.$apply(function () {
scope.isFocus = false;
});
});
}
};
});
Here a working example:
http://plnkr.co/edit/Xan0rO8FKeOAlFC2MwoO?p=preview
HTML:
<div ng-controller="TestController" >
<form name="test_form" ng-submit="submit()">
<input type="text" name="some_name" ng-model="form_data.some_name" required>
<ng-form ng-repeat="key in keys" name="keyForm">
<input type="text" name="data_input" ng-model="form_data.data_input" required>
</ng-form>
<a ng-click="addKey()">NEW KEY</a>
</form>
</div>
JS:
app.controller('TestController', function TestController($scope){
$scope.keys = [];
$scope.addKey = function() {
$scope.keys.push({});
}
$scope.submit = function() {
console.log($scope);
}
});
In submit function I can get the value of "some_name" input:
$scope.submit = function() {
console.log($scope.form_data.some_name);
}
But I can't get the values of "data_input" inputs (they are inside ngform tag). How to do that?
(ngform tag is using for ability to validate each new added input separately)
Each input inside the ng-repeat needs its own unique ng-model property -- they all can't use form_data.data_input. Here is one way to solve your problem:
<ng-form ng-repeat="key in keys" name="keyForm">
<input type="text" name="data_input" ng-model="key.data" required>
</ng-form>
$scope.addKey = function () {
$scope.keys.push({ data: ''});
}
Fiddle.
See also https://stackoverflow.com/a/14379763/215945
I searched and tried many ng-xxxx kind of options but couldn't find the one..
I just want to call some function in the controller when radio button is selected.
So it might be similar to following..(Of course, below code is not working)
<input type="radio" ng-model="value" value="one" ng-click="checkStuff()"/>
Is there any way to achieve what I want?
There are at least 2 different methods of invoking functions on radio button selection:
1) Using ng-change directive:
<input type="radio" ng-model="value" value="foo" ng-change='newValue(value)'>
and then, in a controller:
$scope.newValue = function(value) {
console.log(value);
}
Here is the jsFiddle: http://jsfiddle.net/ZPcSe/5/
2) Watching the model for changes. This doesn't require anything special on the input level:
<input type="radio" ng-model="value" value="foo">
but in a controller one would have:
$scope.$watch('value', function(value) {
console.log(value);
});
And the jsFiddle: http://jsfiddle.net/vDTRp/2/
Knowing more about your the use case would help to propose an adequate solution.
Should use ngChange instead of ngClick if trigger source is not from click.
Is the below what you want ? what exactly doesn't work in your case ?
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.value = "none" ;
$scope.isChecked = false;
$scope.checkStuff = function () {
$scope.isChecked = !$scope.isChecked;
}
}
<div ng-controller="MyCtrl">
<input type="radio" ng-model="value" value="one" ng-change="checkStuff()" />
<span> {{value}} isCheck:{{isChecked}} </span>
</div>
In newer versions of angular (I'm using 1.3) you can basically set the model and the value and the double binding do all the work this example works like a charm:
angular.module('radioExample', []).controller('ExampleController', ['$scope', function($scope) {
$scope.color = {
name: 'blue'
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<html>
<body ng-app="radioExample">
<form name="myForm" ng-controller="ExampleController">
<input type="radio" ng-model="color.name" value="red"> Red <br/>
<input type="radio" ng-model="color.name" value="green"> Green <br/>
<input type="radio" ng-model="color.name" value="blue"> Blue <br/>
<tt>color = {{color.name}}</tt><br/>
</form>
</body>
</html>
For dynamic values!
<div class="col-md-4" ng-repeat="(k, v) in tiposAcesso">
<label class="control-label">
<input type="radio" name="tipoAcesso" ng-model="userLogin.tipoAcesso" value="{{k}}" ng-change="changeTipoAcesso(k)" />
<span ng-bind="v"></span>
</label>
</div>
in controller
$scope.changeTipoAcesso = function(value) {
console.log(value);
};
Another approach is using Object.defineProperty to set valueas a getter setter property in the controller scope, then each change on the value property will trigger a function specified in the setter:
The HTML file:
<input type="radio" ng-model="value" value="one"/>
<input type="radio" ng-model="value" value="two"/>
<input type="radio" ng-model="value" value="three"/>
The javascript file:
var _value = null;
Object.defineProperty($scope, 'value', {
get: function () {
return _value;
},
set: function (value) {
_value = value;
someFunction();
}
});
see this plunker for the implementation
i prefer to use ng-value with ng-if,
[ng-value] will handle trigger changes
<input type="radio" name="isStudent" ng-model="isStudent" ng-value="true" />
//to show and hide input by removing it from the DOM, that's make me secure from malicious data
<input type="text" ng-if="isStudent" name="textForStudent" ng-model="job">
<form name="myForm" ng-submit="submitForm()">
<label data-ng-repeat="i in [1,2,3]"><input type="radio" name="test" ng-model="$parent.radioValue" value="{{i}}"/>{{i}}</label>
<div>currently selected: {{radioValue}}</div>
<button type="submit">Submit</button>
</form>