Detect within link directive whenever input blurred - javascript

I have an input with a link directive. My question is: is it possible to detect within the link function in the directive when the input loses focus?
Here is my directive:
appDrct.directive('formattedDate', ['$filter', 'formatter', function ($filter, formatter) {
return {
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var val = element.val();
if(!val)
return viewValue;
var dateStr = $filter('date')(val,'dd.MM.yyyy');
if(dateStr == undefined)
return viewValue;
var parsed = viewValue;
if(**BLURRED**){
do something....
}
try
{
var dateParts = dateStr.split('.');
parsed = new Date(dateParts[2],dateParts[1]-1,dateParts[0]);
}
catch(e){
}
return parsed;
});
},
restrict: 'A',
require: 'ngModel'
};
}]);
JADE:
input.form-control(formatted-date='mybirth', name='birth' ,placeholder='jj.mm.aaaa', type="text", datepicker-popup="dd.MM.yyyy", ng-model="mybirth", is-open="$parent.opened[0]", close-text="Close")
Plunker of an example:
http://plnkr.co/edit/t9ERna33YcG8ubDqDPgy?p=preview

You may also use element.on('blur', yourFn) in the link function

You can use ng-blur directive please see here http://plnkr.co/edit/Umx2czSRtgh3Cb2rKXYf?p=preview
<p class="input-group">
<input id="birth" formattedDate="mybirth" placeholder="dd.mm.yyyy" type="text" datepicker-popup="dd.MM.yyyy"
ng-model="mybirth" is-open="opened"
ng-blur="action()"
close-text="Close" class="form-control"/><span class="input-group-btn">
<button type="button" ng-click="open($event)" class="btn btn-default"><i class="glyphicon glyphicon-calendar"></i></button></span>
</p>

Related

Reload a directive, to iterate over the elements that use it. in Angular.js

I have a directive that validates all the fields of a form that contain the "validate" directive. In all fields the word "logan" must exist to be correct. At any given time I want and need, when I click on the "Re_Evaluate all the form" button, validate if the form is correct, iterating in all the elements of the form, just like when the $timeout function is executed the first time .
app.directive('validate', function ($timeout,$compile) {
return {
restrict: 'AE',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
if (!ngModel){
return;
}
$timeout(function() {
console.log(ngModel.$viewValue); //I need this, iterate in all elements with the directive 'validate', when re_evaluate() is clicked
if(ngModel.$viewValue=='logan'){
ngModel.$setValidity('validate',true);
}
else{
ngModel.$setValidity('validate',false);
}
})
scope.re_evaluate = function(){
console.log('I need re-evaluate all the form!')
}
}
};
});
http://jsfiddle.net/hmk0yg42/
The HTML is
<section ng-app="app">
<article ng-controller="appCtrl" class="container">
<form class="form-horizontal well" name="zform" invalidate>
<input type="text" name="mytext1" ng-model="my_text" validate />
<input type="text" name="mytext2" ng-model="my_text2" validate />
<input type="text" name="mytext3" ng-model="my_text3" validate />
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-disabled="zform.$invalid">
Validate</button>
</form>
</article>
</section>
And the JS is
var app = angular.module('app', []);
app.controller('appCtrl', function ($scope) {
$scope.my_text='logan';
$scope.my_text2 = 'logan';
$scope.my_text3 = 'logan';
});
app.directive('validate', function () {
return {
restrict: 'AE',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$parsers.unshift(function(value) {
var valid = value == 'logan';
ngModelCtrl.$setValidity('logan',valid);
return value;
});
ngModelCtrl.$formatters.unshift(function(value) {
var valid = value == 'logan';
ngModelCtrl.$setValidity('logan', valid);
return value;
});
}
};
});
you don't need a re-evaluate button

Angularjs directive $compile causing ng-click to fire twice

I created an angular validator module for form validation without the need to include ngMessages in the form and everything is working as expected.
However I discovered a bug which I have been trying to fix. It has something to do with $compile.
So I have a directive that adds attributes to form elements and this is achieved by using $compile service however, it seems the $compile service causes an unwanted behaviour to ng-click so when ng-clicklocated inside the form is called it fires twice;
Here is the directive and what I am doing:
angular.module('app',[])
.directive('validateForm',['$compile',
function($compile)
{
var addErrors = function(rules, form, ctrls, scope, config){
//code
};
return {
restrict: 'A',
require: ['^form'],
link: {
post: function(scope, element, attrs, ctrls){
var form = ctrls[0];
var config = scope.validator;
if(typeof config != 'object') return;
var rules = config['rules'];
var errors = [];
//-----
},
pre: function(scope, element, attrs, ctrls){
var elm = element.find('select, input, textarea').attr('validate-field','');
element.removeAttr("validate-form"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-validate-form");
$compile(element.contents())(scope);
}
}
};
}
])
.controller('UserController',['$scope', function($scope){
$scope.title = 'Form Validator';
$scope.clickThings = function(value){
alert(value); //pops up twice means ng-click fires twice
}
}]);
Form markup:
<div ng-controller="UserController">
<form novalidate="" validate-form name="form" role="form">
<div class="form-group">
<input type="text" class="form-control" ng-model="first_name" name="first_name" />
</div>
<div class="form-group">
<input type="text" class="form-control" ng-model="last_name" name="last_name" />
</div>
<div class="form-group">
<input type="text" class="form-control" ng-model="email" name="email" />
</div>
<div class="form-group">
<input type="password" class="form-control" ng-model="password" name="password" />
</div>
<div class="form-group">
<input type="text" class="form-control" ng-model="country" name="country" />
</div>
<a type="button" class="btn btn-success" ng-click="clickThings('Submit Clicked')">Submit</a>
</form>
</div>
I have created a plunker:
http://embed.plnkr.co/uIid4gczKxKI4rPOHqx7
After trying different things I realized ng-click which is already compile is compiled a second time when $compile(element.contents())(scope) is called.
To resolve this issue, only need to compile the altered/affected elements i.e
elem = element.find('select, input, textarea').attr('validate-field','');
by replacing $compile(element.contents())(scope) with $compile(elem)(scope);
So I ended up with this:
angular.module('app',[])
.directive('validateForm',['$compile',
function($compile)
{
var addErrors = function(rules, form, ctrls, scope, config){
//code
};
return {
restrict: 'A',
require: ['^form'],
link: {
post: function(scope, element, attrs, ctrls){
var form = ctrls[0];
var config = scope.validator;
if(typeof config != 'object') return;
var rules = config['rules'];
var errors = [];
//-----
},
pre: function(scope, element, attrs, ctrls){
var elem = element.find('select, input, textarea').attr('validate-field','');
element.removeAttr("validate-form"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-validate-form");
$compile(elem)(scope);
}
}
};
}
])
.controller('UserController',['$scope', function($scope){
$scope.title = 'Form Validator';
$scope.clickThings = function(value){
alert(value); //pops up twice means ng-click fires twice
}
}]);
Working plunker here:
What is the purpose for using the $compile in a pre-link function? if u just want to do template transformation before the directive element get linked, u should put ur code in directive's compile and take out the $compile. Or if you would like to $compile your element after child elements are linked, u should put ur code in post-link. Putting $compile in pre-link will cause the child nodes of your child elements get linked twice.
Either choose:
angular.module('app',[])
.directive('validateForm',['$compile',
function($compile)
{
var addErrors = function(rules, form, ctrls, scope, config){
//code
};
return {
restrict: 'A',
require: ['^form'],
compile:function(element, attrs, ctrls){
// the code will be executed before get complied
var elm = element.find('select, input, textarea').attr('validate-field','');
return function(scope, element, attrs, ctrls){
var form = ctrls[0];
var config = scope.validator;
if(typeof config != 'object') return;
var rules = config['rules'];
var errors = [];
//-----
}
}
};
}
])
Or
angular.module('app',[])
.directive('validateForm',['$compile',
function($compile)
{
var addErrors = function(rules, form, ctrls, scope, config){
//code
};
return {
restrict: 'A',
require: ['^form'],
link: {
post: function(scope, element, attrs, ctrls){
var form = ctrls[0];
var config = scope.validator;
if(typeof config != 'object') return;
var rules = config['rules'];
var errors = [];
//-----
var elm = element.find('select, input, textarea').attr('validate-field','');
element.removeAttr("validate-form"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-validate-form");
$compile(element.contents())(scope);
},
pre: function(scope, element, attrs, ctrls){
}
}
};
}
])
EDIT
Just eliminate the $compile clause will also do the trick. But these three ways have some difference.
For more information u should refer to the official document

Monitor for $valid on input element in AngularJS directive

I have this directive that prepends an <i> element before each <input> element with add-icon-element attribute. Now what i'm trying to do is to observe validation for each <input> element, so when the user types something in one of them the class of the <i> element that precedes will change to fa-check green-i. I tried to do it by using attrs.$observe to see when the class changes from ng-invalid to ng-valid but it fires only one time when the DOM is structured, it doesn't react to changes in the input element.
What am i doing wrong? is there a way to do it using the input $valid?
I saw some answers regarding one input with suggestions to add names to the form and input - but what can I do if I have multiple inputs that I need to validate and not just one?
angular.module('mean.theme')
.directive("addIconElement", function () {
return {
restrict: 'EA',
link: function (scope, inputElement, attrs) {
var $icon = $('<i class="fa"></i>');
inputElement.before($icon);
attrs.$observe('class', function(val){
if (val.indexOf("ng-valid") >= 0) {
inputElement.prev().addClass('fa-check green-i');
}
});
}
};
});
and this is one of my 'inputs' in the html:
<form role="form" name="createProjectForm" class="form-validation">
<div class="form-group">
<label class="control-label text-center center-block" for="project.name">
Name Your Project
</label>
<div class="input-icon right">
<input type="text" placeholder="type here" name="project.name"
ng-model="project.name" required="required" class="form-control" add-icon-element/>
</div>
</div>
<form>
You don't need create a directive for such case, you could achieve this by using ng-class directive, only change your field name from name="project.name" to name="project_name"
<div class="input-icon right">
<input type="text" placeholder="type here" name="project.name"
ng-class="{'fa-check green-i': createProjectForm.project_name.$valid}"
ng-model="project.name" required="required"
class="form-control"/>
</div>
Update
To make it generic way, you need to require ngModel directive on that element, which will give you access to the ngModelController.
angular.module('mean.theme')
.directive("addIconElement", function () {
return {
restrict: 'EA',
require: 'ngModel', //require to get access to `ngModelController`
link: function (scope, inputElement, attrs, ngModelCtrl) {
var $icon = $('<i class="fa"></i>');
inputElement.before($icon);
scope.$watch(function(){
return ngModelCtrl.$valid; //made watch on field validation.
}, function(val){
if (val.indexOf("ng-valid") >= 0) {
inputElement.prev().addClass('fa-check green-i');
}
});
}
};
});
I think this will do it for you:
https://stackoverflow.com/a/23871934/1636157
angular.module('mean.theme')
.directive("addIconElement", function () {
return {
restrict: 'EA',
require: '^form',
link: function (scope, inputElement, attrs, ctrl) {
var $icon = $('<i class="fa"></i>');
inputElement.before($icon);
scope.$watch(ctrl.$name + '.' + inputElement.attr('name') + '.$valid', function (valid) {
if(valid) {
inputElement.prev().addClass('fa-check green-i');
} else {
inputElement.prev().removeClass('fa-check green-i');
}
});
}
};
});

$dirty set value on focus

I am creating a form in AngularJS and I want validate the fields, the problem is that the required message appear only if write something in the input and after I delete it, but I want that the message appear after to focus the input
my code is the following
<input type="text" name="textInput" data-ng-model="field.data" class="form-control" required/>
<span ng-show="form.textInput.$dirty && form.textInput.$error.required">Required!</span>
Try the following
<span ng-show="form.textInput.$touched && form.textInput.$error.required">Required!</span>
This will show the message after you touched and left(lost focus) with the field invalid. Documentation
Yes, it's doable. First add a directive like this:
myApp.directive('trackFocus', ['$timeout', function($timeout) {
return {
restrict: 'A',
require: 'ngModel',
scope: true,
link: function ($scope, element, attr, ctrl) {
element.on("focus", function() {
$timeout(function() {
ctrl.hasFocus = true;
});
});
element.on("blur", function() {
$timeout(function() {
ctrl.hasFocus = false;
});
});
}
}
}]);
Then use the directive and modify your code:
<input type="text" name="textInput" ng-model="field.data" class="form-control" required track-focus />
<span ng-show="form.textInput.hasFocus && form.textInput.$dirty && form.textInput.$error.required">Required!</span>

How can I count validated inputs (array) in Angular JS?

I cannot figure out how can I count form fields which are valid:
For template i'm using common code:
<p class="input-group" ng-repeat="pomiar in pomiary track by $index">
<input type="number" class="form-control" ng-model="pomiar" is-float/>
<span class="input-group-btn">
<input class="btn btn-danger" ng-click="usunPomiar($index)"
type="button" value="X">
</span>
</p>
Validation is done via directive :
.directive('isFloat', function ($filter) {
var FLOAT_REGEXP_3 = /^\$?\d+(\.\d*)?$/; //Numbers like: 1123.56
var FLOAT_REGEXP_4 = /^\$?\d+(\,\d*)?$/; //Numbers like: 1123,56
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
if (FLOAT_REGEXP_3.test(viewValue)) {
ctrl.$setValidity('float', true);
return parseFloat(viewValue);
} else if (FLOAT_REGEXP_4.test(viewValue)) {
ctrl.$setValidity('float', true);
return parseFloat(viewValue.replace(',', '.'));
}else {
ctrl.$setValidity('float', false);
return undefined;
}
});
ctrl.$formatters.unshift(
function (modelValue) {
return $filter('number')(parseFloat(modelValue) , 2);
}
);
}
};
});
I would like to display nuber of fields(inputs) in the template or store it in variable.
No problem if input isn't array and name attribute 'pomiar' is set:
{{myForm.pomiar.$valid}}
Do I have to write function in controller to validate it once again, or is there simpler way?

Categories