AngularJS: Cannot access form field errors from a directive - angularjs

LIVE DEMO
I use Angular 1.2.18 (have to support IE8), and I'm trying to create something similar to ngMessages that exists in Angular 1.3:
HTML:
<form name="form" novalidate>
<div>
<label for="phone">Phone:</label>
<input id="phone" name="phone" ng-model="phone" type="text"
required ng-minlength="5">
<div form-errors-for="form.phone">
<div form-error="required">Required</div>
<div form-error="minlength">Too short</div>
</div>
</div>
</form>
JS:
angular.module("Validation", [])
.directive("formErrorsFor", function() {
return {
scope: {
model: '=formErrorsFor'
},
controller: function($scope) {
this.model = $scope.model;
}
};
})
.directive("formError", function() {
return {
require: '^formErrorsFor',
link: function(scope, element, attrs, ctrl) {
console.log(ctrl.model.$error); // Always {}. Why??
}
};
});
Unfortunately, accessing form.phone.$error from the formError directive, always results in an empty object. Why it doesn't have the required and the minlength properties?
PLAYGROUND HERE

I tried you jsbin. The issue here is you are trying to access errors too early.
Also the scope on the two directives are different.
I changed you jsbin and it seems to work. I added a watch
scope.$watch(function(){
return ctrl.model.$error;
},function(n,o){
console.log(n);
});
for error changes as it s not defined on scope. See this http://jsbin.com/duxewigi/3/edit

Related

Calling callback function in directive doesn't work

I want the directive to pass a value to the callback function (that was defined in the controller). The function is never called, though, and I have no clue why.
HTML:
<input type='file' fileread success="fileUploaded(data)" name="myFile" id="myFile" />
DIRECTIVE:
myApp.directive('fileread', function() {
return {
scope: {
callBack: '&success',
},
link: function (scope, element) {
scope.callBack({data: "test"});
}
};
});
CONTROLLER:
myApp.controller('MyCtrl', function($scope){
$scope.fileUploaded = function(data){
console.log(data);
};
})
FIDDLE: http://jsfiddle.net/v6r9L6g3/4/
You are missing ng-app and ng-controller in your html
your html must be
<div ng-app="myApp" ng-controller="MyCtrl">
<input type='file' fileread success="fileUploaded(data)" name="myFile" id="myFile" />
</div>
Above will work fine
Alternatively you can use your directive as follow
myApp.directive('fileread', function() {
return {
scope: {
success: '&',
},
link: function (scope, element) {
scope.success({data: "test"});
}
};
});
And
here is working example http://jsfiddle.net/31rpuobL/
The only one trouble with execution of your code was that input have to be surrounded by div with ng-controller directive on it. Like following
<div ng-controller="MyCtrl">
<input type='file' fileread success="fileUploaded(data)" name="myFile" id="myFile" />
</div>
And everything just works perfect.

Attribute directive accessing element and adding a listner

I need to write an attribute directive using Angular 1.5.5 which is basically restricting inputs on keypress event of the text box. So it should look like this
<input type="number" name="age" id="age" restrict-char="['e','-']" />
How can we write an attribute directive without using link function. I dont want to use link function since i will be porting my code base to Angular 2.0 and link functions are not supported there.
Not sure if that is what you want but you can use $parsers on ngModelController and set ng-model-options to update on any event.
angular.module('app', []);
angular.module('app').directive('restrictChar', () => {
return {
restrict: 'A',
require: 'ngModel',
scope: {
restricted: '=restrictChar'
},
controller: function ($scope, $element) {
const ngModel = $element.controller('ngModel');
ngModel.$parsers.unshift((value) => {
const newVal = value
.split('')
.filter((char) => $scope.restricted.indexOf(char) === -1)
.join('');
$element.val(newVal);
return newVal;
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<div ng-app="app">
<input type="text" ng-model="x" name="age" id="age" restrict-char="['e','-']" ng-model-options="{updateOn: 'keyup'}" /><br>
{{x}}
</div>

How do I get my dual binding to work properly with bootstrap datetime picker? [duplicate]

Here is the html for the date field :
<div class='form-group'>
<label>Check out</label>
<input type='text' ng-model='checkOut' class='form-control' data-date-format="yyyy-mm-dd" placeholder="Check out" required id="check-out">
</div>
<script>
$('#check-out').datepicker();
</script>
The datepicker shows up in the input field. However if I do this in my controller :
console.log($scope.checkOut);
I get undefined in the javascript console.
How to solve this ?
Is there a better way to use bootstrap-datepicker with angularjs ?
I don't want to use angular-ui/angular-strap since my project is bloated with javascript libraries.
As #lort suggests, you cannot access the datepicker model from your controller because the datepicker has its own private scope.
If you set: ng-model="parent.checkOut"
and define in the controller: $scope.parent = {checkOut:''};
you can access the datepicker using: $scope.parent.checkOut
I am using bootstrap 3 datepicker https://eonasdan.github.io/bootstrap-datetimepicker/ and angularjs, I had the same problem with ng-model, so I am getting input date value using bootstrap jquery function, below is the code in my controller, it's worked for me.
Html
<input class="form-control" name="date" id="datetimepicker" placeholder="select date">
Controller
$(function() {
//for displaying datepicker
$('#datetimepicker').datetimepicker({
viewMode: 'years',
format: 'DD/MM/YYYY',
});
//for getting input value
$("#datetimepicker").on("dp.change", function() {
$scope.selecteddate = $("#datetimepicker").val();
alert("selected date is " + $scope.selecteddate);
});
});
I just found a solution to this myself. I just pass in the model name to the directive (which I found most of online). This will set the value of the model when the date changes.
<input data-ng-model="datepickertext" type="text" date-picker="datepickertext" />{{datepickertext}}
angular.module('app').directive('datePicker', function() {
var link = function(scope, element, attrs) {
var modelName = attrs['datePicker'];
$(element).datepicker(
{
onSelect: function(dateText) {
scope[modelName] = dateText;
scope.$apply();
}
});
};
return {
require: 'ngModel',
restrict: 'A',
link: link
}
});
I am using Angular JS 1.5.0 and Bootstrap 3 Datetimepicker from https://eonasdan.github.io/bootstrap-datetimepicker/
After some time and struggling, I finally found a solution how to make it work for me :)
JSFiddle: http://jsfiddle.net/aortega/k6ke9n2c/
HTML Code:
<div class="form-group col-sm-4" >
<label for="birthdate" class="col-sm-4">Birthday</label>
<div class="col-sm-8">
<div class="input-group date" id="birthdate" ng-model="vm.Birthdate" date-picker>
<input type="text" class="form-control netto-input" ng-model="vm.Birthdate" date-picker-input>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="form-group col-sm-4">
<label for="birthdateText" class="col-sm-4">Model:</label>
<div class="col-sm-8">
<input type="text" class="form-control netto-input" ng-model="vm.Birthdate">
</div>
</div>
</body>
App.js:
Simply a controller setting the viewmodels Birtdate attribute:
var app = angular.module('exampleApp',[]);
app.controller('ExampleCtrl', ['$scope', function($scope) {
var vm = this;
vm.Birthdate = "1988-04-21T18:25:43-05:00";
}]);
The first directive is initializing the datetimepicker and listening to the dp.change event.
When changed - the ngModel is updated as well.
// DatePicker -> NgModel
app.directive('datePicker', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
$(element).datetimepicker({
locale: 'DE',
format: 'DD.MM.YYYY',
parseInputDate: function (data) {
if (data instanceof Date) {
return moment(data);
} else {
return moment(new Date(data));
}
},
maxDate: new Date()
});
$(element).on("dp.change", function (e) {
ngModel.$viewValue = e.date;
ngModel.$commitViewValue();
});
}
};
});
The second directive is watching the ngModel, and triggering the input onChange event when changed. This will also update the datetimepicker view value.
// DatePicker Input NgModel->DatePicker
app.directive('datePickerInput', function() {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
// Trigger the Input Change Event, so the Datepicker gets refreshed
scope.$watch(attr.ngModel, function (value) {
if (value) {
element.trigger("change");
}
});
}
};
});
I have the same problem and resolve like this
added in html part
<input class="someting" id="datepicker" type="text" placeholder="Dae" ng-model=""/>
and simple in Controller call
$scope.btnPost = function () {
var dateFromHTML = $('#datepicker').val();
Have you tried AngularUI bootstrap? It has all the bootstrap modules rewritten in angular(including datepicker): http://angular-ui.github.io/bootstrap/
One of ways around: set the id field to the input, then call document.getElementById('input_name').value to get the value of the input field.
Using this datepicker I had the same problem. I solved it using a little trick.
In the inputs tag I added a new attribute (dp-model):
<input class="form-control dp" type="text" dp-model="0" />
<input class="form-control dp" type="text" dp-model="1" />
...
And then in the js file I forced the binding in this way:
$scope.formData.dp = []; // arrays of yours datepicker models
$('.dp').datepicker().on('changeDate', function(ev){
$scope.formData.dp[$(ev.target).attr('dp-model')] = $(ev.target).val();
});
This worked for me:
set ng-model="date"
on your angular controller:
$scope.date = '';
$('#check-out').datepicker().on('changeDate', function (ev) {
$scope.date= $('#check-out').val();
$scope.$digest();
$scope.$watch('date', function (newValue, oldValue) {
$scope.date= newValue;
});
});
My actual trouble was that the value of the model was not reflected till another component on the scope was changed.
im using this , and my code :
this.todayNow = function () {
var rightNow = new Date();
return rightNow.toISOString().slice(0,10);
};
$scope.selecteddate = this.todayNow();
$(function() {
//for displaying datepicker
$('.date').datepicker({
format: 'yyyy-mm-dd',
language:'fa'
});
//for getting input value
$('.date').on("changeDate", function() {
$scope.selecteddate = $(".date").val();
});
});
To solve this, I have my HTML looking like this:
<div class='input-group date' id='datetimepicker1'>
<input type='text' ng-model="date.arrival" name="arrival" id="arrival"
class="form-control" required />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
My ng-model wouldn't update, so I used this to fix it:
$("#datetimepicker1").on("dp.change", function (e) {
$scope.date.arrival = $("#arrival").val(); // pure magic
$('#datetimepicker2').data("DateTimePicker").minDate(e.date); // this line is not relevant for this example
});

How to create a directive for disable all elements into div element

how to create a directive for disable all elements into div element ?
something like this :
<div div-disabled div-disabled-condition="state=='Stack'||state=='Over'||state=='Flow'">
<input type="text"/>
<input type="url"/>
<div>
<input type="text"/>
<input type="url"/>
</div>
<div>
Is it possible? I have no idea .
angular
.module('uiRouterApp.ctrl.add', ['uiRouterApp.ctrl.customDirective'])
.controller('addCtrl', [
'$scope',
'$location',
'$stateParams',
'$state',
function ($scope, $location, $stateParams, $state) {
$scope.state = {};
}
]).directive('divDisabled', function () {
return {
scope: {
divDisabledCondition: '#'
},
link: function (scope, element, attrs) {
}
};
});
Update :
please see this :
<div class="col-sm-12 ng-isolate-scope" selected-object="SelectedAutoComplete" local-data="requirements.Item1" search-fields="NameFa,NameEn" title-field="NameFa" minlength="2" field-required="true" image-field="ImageUrl" disable-auto-compelete="response.State=='Success'||response.State=='Error'||response.State=='Warning'">
<div class="angucomplete-holder">
<input id="_value" ng-model="searchStr" type="text" placeholder="select" class="form-control ng-dirty" ng-focus="resetHideResults()" ng-blur="hideResults()" autocapitalize="off" autocorrect="off" autocomplete="off" ng-change="inputChangeHandler(searchStr)" ng-disabled="response.State=='Success'||response.State=='Error'||response.State=='Warning'" style="">
<!-- ngIf: showDropdown -->
</div>
</div>
directive :
.directive('contentsDisabled', function() {
return {
compile: function(tElem, tAttrs) {
var inputs = tElem.find('input');
for (var i = 0; i < inputs.length; i++) {
inputs.attr('ng-disabled', tAttrs['disableAutoCompelete']);
}
}
}
})
why When the state is 'Success' or 'Error' or 'Warning' Input not disabled ?
You can create a directive that alters its content during compile time by adding the condition. Something along these lines (untested):
module.directive('contentsDisabled', function() {
return {
compile: function(tElem, tAttrs) {
var inputs = tElem.find('input');
inputs.attr('ng-disabled', tAttrs['contentsDisabled']);
}
};
});
See a JSFiddle here: http://jsfiddle.net/HB7LU/6380/
This has the drawback that you just copy the expression from contents-disabled into ng-disabled attributes of any inputs - if somebody uses a directive that in turn creates <input> elements, you won't pick them up.
It'd be less fragile to get hold of the FormController instance and iterate through all its controls, but sadly AngularJS doesn't expose the controls in a form. Maybe file a feature request?
You also can use a tag fieldset :
<form>
<fieldset ng-disable="foo">
<input name="the_one"/>
<input name="the_second"/>
</fieldset>
<input name="the_thrid"/>
</form>
With this way, when the variable foo is TRUE, inputs "the_one" and "the_second" will be disabled.
Why don't you use ng-disabled on your required expression on each input?
https://docs.angularjs.org/api/ng/directive/ngDisabled
If you truly do want a grouping directive, use the compile function of the directive to insert the ng-disabled attribute on each child. Or use a paren't child directive to signify which children to apply the ng-disabled to.
There is a new option to control enable/disable input field for angucomplete-alt.
http://ghiden.github.io/angucomplete-alt/#example13

Dynamic validation and name in a form with AngularJS

I have this form : http://jsfiddle.net/dfJeN/
As you can see the name value for the input is statically set :
name="username"
, the form validation works fine (add something and remove all text from the input, a text must appears).
Then I try to dynamically set the name value : http://jsfiddle.net/jNWB8/
name="{input.name}"
Then I apply this to my validation
login.{{input.name}}.$error.required
(this pattern will be used in an ng-repeat) but my form validation is broken. It is correctly interpreted in my browser (if I inspect the element I saw login.username.$error.required).
Any Idea ?
EDIT: After logging the scope in the console it appears that the
{{input.name}}
expression is not interpolate. My form as an {{input.name}} attribute but no username.
UPDATE: Since 1.3.0-rc.3 name="{{input.name}}" works as expected. Please see #1404
You can't do what you're trying to do that way.
Assuming what you're trying to do is you need to dynamically add elements to a form, with something like an ng-repeat, you need to use nested ng-form to allow validation of those individual items:
<form name="outerForm">
<div ng-repeat="item in items">
<ng-form name="innerForm">
<input type="text" name="foo" ng-model="item.foo" />
<span ng-show="innerForm.foo.$error.required">required</span>
</ng-form>
</div>
<input type="submit" ng-disabled="outerForm.$invalid" />
</form>
Sadly, it's just not a well-documented feature of Angular.
Using nested ngForm allows you to access the specific InputController from within the HTML template. However, if you wish to access it from another controller it does not help.
e.g.
<script>
function OuterController($scope) {
$scope.inputName = 'dynamicName';
$scope.doStuff = function() {
console.log($scope.formName.dynamicName); // undefined
console.log($scope.formName.staticName); // InputController
}
}
</script>
<div controller='OuterController'>
<form name='myForm'>
<input name='{{ inputName }}' />
<input name='staticName' />
</form>
<a ng-click='doStuff()'>Click</a>
</div>
I use this directive to help solve the problem:
angular.module('test').directive('dynamicName', function($compile, $parse) {
return {
restrict: 'A',
terminal: true,
priority: 100000,
link: function(scope, elem) {
var name = $parse(elem.attr('dynamic-name'))(scope);
// $interpolate() will support things like 'skill'+skill.id where parse will not
elem.removeAttr('dynamic-name');
elem.attr('name', name);
$compile(elem)(scope);
}
};
});
Now you use dynamic names wherever is needed just the 'dynamic-name' attribute instead of the 'name' attribute.
e.g.
<script>
function OuterController($scope) {
$scope.inputName = 'dynamicName';
$scope.doStuff = function() {
console.log($scope.formName.dynamicName); // InputController
console.log($scope.formName.staticName); // InputController
}
}
</script>
<div controller='OuterController'>
<form name='myForm'>
<input dynamic-name='inputName' />
<input name='staticName' />
</form>
<a ng-click='doStuff()'>Click</a>
</div>
The problem should be fixed in AngularJS 1.3, according to this discussion on Github.
Meanwhile, here's a temporary solution created by #caitp and #Thinkscape:
// Workaround for bug #1404
// https://github.com/angular/angular.js/issues/1404
// Source: http://plnkr.co/edit/hSMzWC?p=preview
app.config(['$provide', function($provide) {
$provide.decorator('ngModelDirective', function($delegate) {
var ngModel = $delegate[0], controller = ngModel.controller;
ngModel.controller = ['$scope', '$element', '$attrs', '$injector', function(scope, element, attrs, $injector) {
var $interpolate = $injector.get('$interpolate');
attrs.$set('name', $interpolate(attrs.name || '')(scope));
$injector.invoke(controller, this, {
'$scope': scope,
'$element': element,
'$attrs': attrs
});
}];
return $delegate;
});
$provide.decorator('formDirective', function($delegate) {
var form = $delegate[0], controller = form.controller;
form.controller = ['$scope', '$element', '$attrs', '$injector', function(scope, element, attrs, $injector) {
var $interpolate = $injector.get('$interpolate');
attrs.$set('name', $interpolate(attrs.name || attrs.ngForm || '')(scope));
$injector.invoke(controller, this, {
'$scope': scope,
'$element': element,
'$attrs': attrs
});
}];
return $delegate;
});
}]);
Demo on JSFiddle.
Nice one by #EnISeeK.... but i got it to be more elegant and less obtrusive to other directives:
.directive("dynamicName",[function(){
return {
restrict:"A",
require: ['ngModel', '^form'],
link:function(scope,element,attrs,ctrls){
ctrls[0].$name = scope.$eval(attrs.dynamicName) || attrs.dynamicName;
ctrls[1].$addControl(ctrls[0]);
}
};
}])
Just a little improvement over EnlSeek solution
angular.module('test').directive('dynamicName', ["$parse", function($parse) {
return {
restrict: 'A',
priority: 10000,
controller : ["$scope", "$element", "$attrs",
function($scope, $element, $attrs){
var name = $parse($attrs.dynamicName)($scope);
delete($attrs['dynamicName']);
$element.removeAttr('data-dynamic-name');
$element.removeAttr('dynamic-name');
$attrs.$set("name", name);
}]
};
}]);
Here is a plunker trial. Here is detailed explantion
I expand the #caitp and #Thinkscape solution a bit, to allow dynamically created nested ng-forms, like this:
<div ng-controller="ctrl">
<ng-form name="form">
<input type="text" ng-model="static" name="static"/>
<div ng-repeat="df in dynamicForms">
<ng-form name="form{{df.id}}">
<input type="text" ng-model="df.sub" name="sub"/>
<div>Dirty: <span ng-bind="form{{df.id}}.$dirty"></span></div>
</ng-form>
</div>
<div><button ng-click="consoleLog()">Console Log</button></div>
<div>Dirty: <span ng-bind="form.$dirty"></span></div>
</ng-form>
</div>
Here is my demo on JSFiddle.
I used Ben Lesh's solution and it works well for me. But one problem I faced was that when I added an inner form using ng-form, all of the form states e.g. form.$valid, form.$error etc became undefined if I was using the ng-submit directive.
So if I had this for example:
<form novalidate ng-submit="saveRecord()" name="outerForm">
<!--parts of the outer form-->
<ng-form name="inner-form">
<input name="someInput">
</ng-form>
<button type="submit">Submit</button>
</form>
And in the my controller:
$scope.saveRecord = function() {
outerForm.$valid // this is undefined
}
So I had to go back to using a regular click event for submitting the form in which case it's necessary to pass the form object:
<form novalidate name="outerForm"> <!--remove the ng-submit directive-->
<!--parts of the outer form-->
<ng-form name="inner-form">
<input name="someInput">
</ng-form>
<button type="submit" ng-click="saveRecord(outerForm)">Submit</button>
</form>
And the revised controller method:
$scope.saveRecord = function(outerForm) {
outerForm.$valid // this works
}
I'm not quite sure why this is but hopefully it helps someone.
This issue has been fixed in Angular 1.3+
This is the correct syntax for what you are trying to do:
login[input.name].$invalid
if we set dynamic name for a input like the below
<input name="{{dynamicInputName}}" />
then we have use set validation for dynamic name like the below code.
<div ng-messages="login.dynamicInputName.$error">
<div ng-message="required">
</div>
</div>

Resources