AngularJS datetimepicker directive not work when change value - angularjs

I have a problem with datetimepicker in AngularJS. When the page loaded, datetimepicker directive run, and I got the right value I want. But when I chose another date, directive does not work, although I have to change the event inside.
A few days ago, It worked, but not now. I tested many times. I don't know why, because I didn't change anything.
The code:
.directive("datetimeselect", [
"Config", function (Config) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, el, attr, ngModel) {
$(el).datetimepicker({
format: Config.defaultConfig.dateTimeFormat
});
el.on('dp.change', function (event) {
scope.$apply(function () {
var date = moment(event.date);
ngModel.$setViewValue(date.format(Config.defaultConfig.dateTimeFormat));
});
});
//format text from the user (view to model)
ngModel.$parsers.push(function (data) {
return moment(data).format(Config.defaultConfig.dateTimeFormat);
});
//format text going to user (model to view)
ngModel.$formatters.push(function (data) {
return moment(data).format(Config.defaultConfig.dateTimeFormat);
});
}
};
}
])
And this is HTML
<div class="form-group col-md-6">
<label for="ToTime" class="control-label">To Time</label>
<input type="text" class="form-control" name="ToTime" id="ToTime"
ng-model="record.ToTime" datetimeselect />
</div>

The $parser is unnecessary and the $formatter needs to set the date:
function postLink(scope, element, attr, ngModel) {
var ignoreChangeEvent = false;
element.datetimepicker();
element.on('dp.change', function(event) {
if (ignoreChangeEvent) {
ignoreChangeEvent = false;
return;
}
scope.$apply(function() {
ngModel.$setViewValue(event.date);
});
});
ngModel.$formatters.push(function (date) {
ignoreChangeEvent = true;
element.data("DateTimePicker").setDate(date);
});
}
The DEMO
angular.module('bootstrap-timepicker', [])
.directive('datetimepicker', [
function() {
return {
restrict: 'A',
link: postLink,
require: 'ngModel'
};
function postLink(scope, element, attr, ngModel) {
var ignoreChangeEvent = false;
element.datetimepicker();
element.on('dp.change', function(event) {
if (ignoreChangeEvent) {
ignoreChangeEvent = false;
return;
}
scope.$apply(function() {
ngModel.$setViewValue(event.date);
});
});
ngModel.$formatters.push(function (date) {
ignoreChangeEvent = true;
element.data("DateTimePicker").setDate(date);
});
}
}
])
.controller('IndexController', function($scope) {
$scope.date = new Date();
});
<link rel="stylesheet" href="//unpkg.com/bootstrap#3/dist/css/bootstrap.css">
<link rel="stylesheet" href="//unpkg.com/bootstrap#3/dist/css/bootstrap-theme.css">
<link rel="stylesheet" href="//unpkg.com/bootstrap-datetime-picker#2.3/css/bootstrap-datetimepicker.css">
<script src="//unpkg.com/jquery#2"></script>
<script src="//unpkg.com/bootstrap#3/dist/js/bootstrap.js"></script>
<script src="//unpkg.com/moment"></script>
<script src="//unpkg.com/eonasdan-bootstrap-datetimepicker#3/src/js/bootstrap-datetimepicker.js"></script>
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="bootstrap-timepicker">
<div class="container" ng-controller="IndexController">
<h4>Datetimepicker</h4>
<div class="form-group">
<div class='input-group date' datetimepicker ng-model="date">
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<p>
ng-model value: {{date}}
</p>
<div class='input-group date' datetimepicker ng-model="date">
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</body>

Related

AngularJS - input type="number" not clearable for non-number (NaN)

Clear number input type does not work for 'e' number
When I clear the input field with input eee in number type, it does not get cleared. Any other input numbers get cleared. Check the JSFiddle. Any hints would be appreciated.
http://jsfiddle.net/2ankx9up/
<div ng-app="app">
<div ng-controller="MainCtrl">
<input type="number" class="form-control" data-ng-model="searchAll">
</input>
<a class="clear" href="" data-ng-click="clearSearch()">X</a>
</div>
</div>
var app = angular.module("app", []);
app.controller("MainCtrl", function ($scope) {
$scope.searchAll = "";
$scope.clearSearch = function () {
$scope.searchAll = "";
};
});
The ng-model directive is unable to clear the content of an <input type="number"> element when that content parses to NaN (not a number). This can happen when a user pastes invalid content or simply types "eee".
One fix is to add a custom directive:
app.directive('clearNan', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
ngModel.$formatters.push(function(value) {
if (!value) elem.val(null);
return value;
});
}
};
})
Usage:
<input type="number" clear-nan ng-model="x" />
The DEMO
angular.module('numfmt-error-module', [])
.directive('clearNan', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
ngModel.$formatters.push(function(value) {
if (!value) elem.val(null);
return value;
});
}
};
})
.run(function($rootScope) {
$rootScope.typeOf = function(value) {
return typeof value;
};
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="numfmt-error-module">
<input clear-nan type="number" ng-model="x" />
<br>
{{ x }} : {{ typeOf(x) }}
<br>
<button ng-click="x=''">Clear input</button>
</body>

Bootstrap DateTimePicker with AngularJS: Passing directive ngModel value to controller

I am trying to get angular bootstrap datetimepicker input value using a custom directive like shown below. I am able to get the value in directive. How can i access this directive scope value in angular controller.
HTML
<div class='input-group date' id='datetimepickerId' datetimez ng-model="dueDate" >
<input type='text' class="form-control" />
</div>
Controller
App.directive('datetimez', function(){
return {
require: '?ngModel',
restrict: 'A',
link: function(scope, element, attrs, ngModel){
if(!ngModel) return;
ngModel.$render = function(){
element.find('#datetimepickerId').val( ngModel.$viewValue || '' );
};
element.datetimepicker({
format : 'YYYY-MM-DD HH:mm:ss'
});
element.on('dp.change', function(){
scope.$apply(read);
});
read();
function read() {
var value = element.find('#datetimepickerId').val();
ngModel.$setViewValue(value);
console.log(scope.dueDate);
}
}
};
});
App.controller('myController', ['$scope', function($scope) {
console.log($scope.dueDate);
}]);
Log inside the directive prints value successfully. But log inside controller does not.
Here you go.
I checked the documentation of the bootstrap datetimepicker and come to know there are two implementation.
One with a icon to click and show the datetimepicker
Another one just with a textbox without a icon
For the first one, you have to use the parent div to initiate the plugin and for the second option, you have to use the textbox to initiate the plugin
You have used the second option but used the parent div to initiate the plugin with a directive.
Also, div elements won't support the ngModel, hence directive should be used with the input element.
I have extended your directive to handle both scenarios and also the date format and other options can be passed from the controller.
You can give a try with the below working snippet.
var App = angular.module('App', []);
App.directive('datetimez', function(){
return {
require: '?ngModel',
restrict: 'A',
link: function(scope, element, attrs, ngModel){
if(!ngModel) return;
ngModel.$render = function(){
element.val( ngModel.$viewValue || '' );
};
function read() {
var value = element.val();
ngModel.$setViewValue(value);
//console.log(scope.dueDate);
}
var options = scope.$eval(attrs.datetimez) || {};
if(element.next().is('.input-group-addon')) {
var parentElm = $(element).parent();
parentElm.datetimepicker(options);
parentElm.on('dp.change', function(){
scope.$apply(read);
});
} else {
element.datetimepicker(options);
element.on('dp.change', function(){
scope.$apply(read);
});
}
read();
}
};
});
App.controller('myController', ['$scope', function($scope) {
$scope.datePickerOptions = {
format : 'YYYY-MM-DD HH:mm:ss'
};
$scope.$watch('dueDate1', function(){
console.log($scope.dueDate1);
});
$scope.$watch('dueDate2', function(){
console.log($scope.dueDate2);
});
}]);
angular.bootstrap(document, ['App']);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-controller="myController">
<div class="row">
<div class='col-md-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" datetimez="datePickerOptions" ng-model="dueDate1" />
</div>
</div>
</div>
</div>
<div class="row">
<div class='col-md-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" datetimez="datePickerOptions" ng-model="dueDate2" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>

How to run customed directive and normal ng-directive also

I have an input to confirm the email twice,
However, When I used the check-email directive and the required validation is not working any more.
Any suggestion? I don't want user keeps this field blank
html
<input type="text"
id="confirm_email_booking"
name="confirm_email_booking"
class="form-control"
check-email
ng-model="payment_contact.confirm_email_booking"
/>
JS
app.directive('checkEmail', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue, $scope) {
var notMatch = (viewValue != scope.form.email_booking.$viewValue)
ctrl.$setValidity('notMatch', !notMatch)
return notMatch;
})
}
}
})
You can just check if the value is present in your directive, as below:
var notMatch = viewValue && viewValue != scope.form.email_booking.$viewValue;
Then you could have something like this:
(function() {
"use strict";
angular
.module('app', [])
.controller('MainCtrl', MainCtrl)
.directive('checkEmail', checkEmail);
MainCtrl.$inject = ['$scope'];
function MainCtrl($scope) {
}
function checkEmail() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue, $scope) {
var notMatch = viewValue && viewValue != scope.form.email_booking.$viewValue;
ctrl.$setValidity('notMatch', !notMatch);
return notMatch;
})
}
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body ng-controller="MainCtrl">
<div class="col-md-12">
<form name="form">
<input type="text" id="email_booking" name="email_booking" class="form-control" ng-model="payment_contact.email_booking" />
<hr>
<input type="text" id="confirm_email_booking" name="confirm_email_booking" class="form-control" check-email ng-model="payment_contact.confirm_email_booking" required />
<span class="text-danger" ng-if="form.confirm_email_booking.$error.required">
Required!
</span>
<span class="text-danger" ng-if="form.confirm_email_booking.$error.notMatch">
NotMatch!
</span>
<pre ng-bind="form.confirm_email_booking | json"></pre>
</form>
</div>
</body>
</html>

Angular bootstrap datepicker date format does not format ng-model value

I am using bootstrap date-picker in my angular application. However when I select a date from that date-picker underlying ng-model that I have bind gets updated I want that ng-model in one date format 'MM/dd/yyyy'. but it every times makes date like this
"2009-02-03T18:30:00.000Z"
instead of
02/04/2009
I have created a plunkr for the same plunkr link
My Html and controller code is like below
<!doctype html>
<html ng-app="plunker">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="DatepickerDemoCtrl">
<pre>Selected date is: <em>{{dt | date:'MM/dd/yyyy' }}</em></pre>
<p>above filter will just update above UI but I want to update actual ng-modle</p>
<h4>Popup</h4>
<div class="row">
<div class="col-md-6">
<p class="input-group">
<input type="text" class="form-control"
datepicker-popup="{{format}}"
ng-model="dt"
is-open="opened" min-date="minDate"
max-date="'2015-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>
</div>
</div>
<!--<div class="row">
<div class="col-md-6">
<label>Format:</label> <select class="form-control" ng-model="format" ng-options="f for f in formats"><option></option></select>
</div>
</div>-->
<hr />
{{dt}}
</div>
</body>
</html>
Angular controller
angular.module('plunker', ['ui.bootstrap']);
var DatepickerDemoCtrl = function ($scope) {
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.format = 'dd-MMMM-yyyy';
};
UPDATE
I am calling below method for posting my data and VAR is array of size 900 which contains date-picker variables.
public SaveCurrentData(formToSave: tsmodels.ResponseTransferCalculationModelTS) {
var query = this.EntityQuery.from('SaveFormData').withParameters({
$method: 'POST',
$encoding: 'JSON',
$data: {
VAR: formToSave.VAR,
X: formToSave.X,
CurrentForm: formToSave.currentForm,
}
});
var deferred = this.q.defer();
this.manager.executeQuery(query).then((response) => {
deferred.resolve(response);
}, (error) => {
deferred.reject(error);
});
return deferred.promise;
}
Although similar answers have been posted I'd like to contribute what seemed to be the easiest and cleanest fix to me. Assuming you are using the AngularUI datepicker and your initial value for the ng-Model does not get formatted simply adding the following directive to your project will fix the issue:
angular.module('yourAppName')
.directive('datepickerPopup', function (){
return {
restrict: 'EAC',
require: 'ngModel',
link: function(scope, element, attr, controller) {
//remove the default formatter from the input directive to prevent conflict
controller.$formatters.shift();
}
}
});
I found this solution in the Github AngularUI issues and therefore all credit goes to the people over there.
You can make use of $parsers as shown below,this solved it for me.
window.module.directive('myDate', function(dateFilter) {
return {
restrict: 'EAC',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue,'yyyy-MM-dd');
});
}
};
});
HTML:
<p class="input-group datepicker" >
<input
type="text"
class="form-control"
name="name"
datepicker-popup="yyyy-MM-dd"
date-type="string"
show-weeks="false"
ng-model="data[$parent.editable.name]"
is-open="$parent.opened"
min-date="minDate"
close-text="Close"
ng-required="{{editable.mandatory}}"
show-button-bar="false"
close-on-date-selection="false"
my-date />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</p>
I ran into the same problem and after a couple of hours of logging and investigating, I fixed it.
It turned out that for the first time the value is set in a date picker, $viewValue is a string so the dateFilter displays it as is. All I did is parse it into a Date object.
Search for that block in ui-bootstrap-tpls file
ngModel.$render = function() {
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
and replace it by:
ngModel.$render = function() {
ngModel.$viewValue = new Date(ngModel.$viewValue);
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
Hopefully this will help :)
The format specified through datepicker-popup is just the format for the displayed date. The underlying ngModel is a Date object. Trying to display it will show it as it's default, standard-compliant rapresentation.
You can show it as you want by using the date filter in the view, or, if you need it to be parsed in the controller, you can inject $filter in your controller and call it as $filter('date')(date, format). See also the date filter docs.
You may use formatters after picking value inside your datepicker directive.
For example
angular.module('foo').directive('bar', function() {
return {
require: '?ngModel',
link: function(scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.push(function(value) {
if (value) {
// format and return date here
}
return undefined;
});
}
};
});
LINK.
With so many answers already written, Here's my take.
With Angular 1.5.6 & ui-bootstrap 1.3.3 , just add this on the model & you are done.
ng-model-options="{timezone: 'UTC'}"
Note: Use this only if you are concerned about the date being 1 day behind & not bothered with extra time of T00:00:00.000Z
Updated Plunkr Here :
http://plnkr.co/edit/nncmB5EHEUkZJXRwz5QI?p=preview
All proposed solutions didn't work for me but the closest one was from #Rishii.
I'm using AngularJS 1.4.4 and UI Bootstrap 0.13.3.
.directive('jsr310Compatible', ['dateFilter', 'dateParser', function(dateFilter, dateParser) {
return {
restrict: 'EAC',
require: 'ngModel',
priority: 1,
link: function(scope, element, attrs, ngModel) {
var dateFormat = 'yyyy-MM-dd';
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue, dateFormat);
});
ngModel.$validators.date = function (modelValue, viewValue) {
var value = modelValue || viewValue;
if (!attrs.ngRequired && !value) {
return true;
}
if (angular.isNumber(value)) {
value = new Date(value);
}
if (!value) {
return true;
}
else if (angular.isDate(value) && !isNaN(value)) {
return true;
}
else if (angular.isString(value)) {
var date = dateParser.parse(value, dateFormat);
return !isNaN(date);
}
else {
return false;
}
};
}
};
}])
I can fix this by adding below code in my JSP file. Now both model and UI values are same.
<div ng-show="false">
{{dt = (dt | date:'dd-MMMM-yyyy') }}
</div>
Steps to change the default date format of ng-model
For different date formats check the jqueryui datepicker date format values here for example I have used dd/mm/yy
Create angularjs directive
angular.module('app', ['ui.bootstrap']).directive('dt', function () {
return {
restrict: 'EAC',
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
ngModel.$parsers.push(function (viewValue) {
return dateFilter(viewValue, 'dd/mm/yy');
});
}
}
});
Write dateFilter function
function dateFilter(val,format) {
return $.datepicker.formatDate(format,val);
}
In html page write the ng-modal attribute
<input type="text" class="form-control" date-type="string" uib-datepicker-popup="{{format}}" ng-model="src.pTO_DATE" is-open="popup2.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" show-button-bar="false" show-weeks="false" dt />
The datepicker (and datepicker-popup) directive requires that the ng-model be a Date object. This is documented here.
If you want ng-model to be a string in specific format, you should create a wrapper directive. Here is an example (Plunker):
(function () {
'use strict';
angular
.module('myExample', ['ngAnimate', 'ngSanitize', 'ui.bootstrap'])
.controller('MyController', MyController)
.directive('myDatepicker', myDatepickerDirective);
MyController.$inject = ['$scope'];
function MyController ($scope) {
$scope.dateFormat = 'dd MMMM yyyy';
$scope.myDate = '30 Jun 2017';
}
myDatepickerDirective.$inject = ['uibDateParser', '$filter'];
function myDatepickerDirective (uibDateParser, $filter) {
return {
restrict: 'E',
scope: {
name: '#',
dateFormat: '#',
ngModel: '='
},
required: 'ngModel',
link: function (scope) {
var isString = angular.isString(scope.ngModel) && scope.dateFormat;
if (isString) {
scope.internalModel = uibDateParser.parse(scope.ngModel, scope.dateFormat);
} else {
scope.internalModel = scope.ngModel;
}
scope.open = function (event) {
event.preventDefault();
event.stopPropagation();
scope.isOpen = true;
};
scope.change = function () {
if (isString) {
scope.ngModel = $filter('date')(scope.internalModel, scope.dateFormat);
} else {
scope.ngModel = scope.internalModel;
}
};
},
template: [
'<div class="input-group">',
'<input type="text" readonly="true" style="background:#fff" name="{{name}}" class="form-control" uib-datepicker-popup="{{dateFormat}}" ng-model="internalModel" is-open="isOpen" ng-click="open($event)" ng-change="change()">',
'<span class="input-group-btn">',
'<button class="btn btn-default" ng-click="open($event)"> <i class="glyphicon glyphicon-calendar"></i> </button>',
'</span>',
'</div>'
].join('')
}
}
})();
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-app="myExample">
<div ng-controller="MyController">
<p>
Date format: {{dateFormat}}
</p>
<p>
Value: {{myDate}}
</p>
<p>
<my-datepicker ng-model="myDate" date-format="{{dateFormat}}"></my-datepicker>
</p>
</div>
</body>
</html>
Defining a new directive to work around a bug is not really ideal.
Because the datepicker displays later dates correctly, one simple workaround could be just setting the model variable to null first, and then to the current date after a while:
$scope.dt = null;
$timeout( function(){
$scope.dt = new Date();
},100);
After checking the above answers, I came up with this and it worked perfectly without having to add an extra attribute to your markup
angular.module('app').directive('datepickerPopup', function(dateFilter) {
return {
restrict: 'EAC',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue, 'yyyy-MM-dd');
});
}
}
});
Finally I got work around to the above problem. angular-strap has exactly the same feature that I am expecting. Just by applying date-format="MM/dd/yyyy" date-type="string" I got my expected behavior of updating ng-model in given format.
<div class="bs-example" style="padding-bottom: 24px;" append-source>
<form name="datepickerForm" class="form-inline" role="form">
<!-- Basic example -->
<div class="form-group" ng-class="{'has-error': datepickerForm.date.$invalid}">
<label class="control-label"><i class="fa fa-calendar"></i> Date <small>(as date)</small></label>
<input type="text" autoclose="true" class="form-control" ng-model="selectedDate" name="date" date-format="MM/dd/yyyy" date-type="string" bs-datepicker>
</div>
<hr>
{{selectedDate}}
</form>
</div>
here is working plunk link

Angular setValidity not working?

I first using setValidity to make a directive in Angular.but not as my expected,here is my code:
angular.module('myApp', [])
.controller('ctrl',function($scope){
$scope.pw='';
})
.directive('pwCheck', function(){
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
elem.on('keyup', function () {
scope.$apply(function () {
var len = elem.val().length;
if(len===0){
ctrl.$setValidity('zero',true);
} else if(len>1 && len<6){
ctrl.$setValidity('one',true);
} else {
ctrl.$setValidity('two',true);
}
});
});
}
};
});
HTML:
<body ng-controller="ctrl">
<form id="myForm" name="myForm">
<input type="text" ng-model="pw" pw-check />
{{myForm.$error}}
<div class="msg-block" ng-show="myForm.$error">
<span class="msg-error" ng-show="myForm.pw.$error.zero">
Input a password.
</span>
<span class="msg-error" ng-show="myForm.pw.$error.one">
Passwords too short.
</span>
<span class="msg-error" ng-show="myForm.pw.$error.two">
Great.
</span>
</div>
</form>
</body>
Online Demo:
http://jsbin.com/cefecicu/1/edit
I think you need:
//Reset your validity
ctrl.$setValidity('zero',true);
ctrl.$setValidity('one',true);
ctrl.$setValidity('two',true);
if(len===0){
ctrl.$setValidity('zero',false);
} else if(len>=1 && len<6){ //use len>=1 instead
ctrl.$setValidity('one',false);
} else {
ctrl.$setValidity('two',false);
}
Using false to indicate errors (not valid):
And give a name to your input:
<input type="text" ng-model="pw" name="pw" pw-check />
http://jsbin.com/cefecicu/11/edit

Resources