Angularjs directive to make form dirty without ng-model - angularjs

I am using Angular 1.5.1. I have a checkbox on my form. I do not care about the truth/false indicator of the checkbox being checked/unchecked and so I do not want ng-model on it. What I care for is:
when checkbox is unchecked, I delete a specific array from my model
when checkbox is checked, I add an empty array back to my model
So I have created a directive that provides me with this functionality, very simple:
.directive('cbOnChecked', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
element.on('click', function(event) {
if(element[0].checked)
scope.$apply(attr.cbOnChecked);
});
}
};
})
.directive('cbOnUnchecked', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
element.on('click', function(event) {
if(!element[0].checked)
scope.$apply(attr.cbOnUnchecked);
});
}
};
})
Now I can do something like:
<input type="checkbox" cb-on-checked="counter = counter + 1" cb-on-unchecked="counter = counter - 1"/>
Or
<input type="checkbox" cb-on-checked="deleteUserList()" cb-on-unchecked="users = []"/> No users<br/>
The problem with this is - the form within which the checkbox is won't get marked as $dirty if there is no ng-model on the checkbox. Is there any way around this?
Here is an example js-fiddle. Thanks.

If you really want to go with your own directives you can just require parent form controller and mark it $dirty manually:
.directive('cbOnChecked', function() {
return {
require: '^form',
restrict: 'A',
link: function(scope, element, attr, ngFormController) {
element.on('click', function(event) {
ngFormController.$setDirty();
if(element[0].checked)
scope.$apply(attr.cbOnChecked);
});
}
};
})

Related

AngularJs - Bootstrap Toggle not able to get check box values

I am using Bootstrap Toggle for my AngularJs project. I created angular directive for this plugin.
myApp.directive('iosToggle', function(){
return {
restrict: 'A',
link: function(scope, element, attrs){
$(element).bootstrapToggle(scope.$eval(attrs.iosToggle));
}
};
});
and using directive in my view
<input type="checkbox" id="myInterview" data-ios-toggle="toggle" data-style="ios" data-onstyle="info" data-size="small" data-on="On" data-off="Off" ng-model="myData.myInterview">
I am getting same design and able to on or off, but When i submit the form, i am not getting check box values.
Yes, I have updated my directive with $watch on change and then updated the model. It works.
myApp.directive('iosToggle', function($timeout){
return {
restrict: 'A',
transclude: true,
replace: false,
require: 'ngModel',
link: function ($scope, $element, $attr, ngModel) {
// update model from Element
var updateModelFromElement = function() {
// If modified
var checked = $element.prop('checked');
if (checked !== ngModel.$viewValue) {
// Update ngModel
ngModel.$setViewValue(checked);
$scope.$apply();
}
};
// Update input from Model
var updateElementFromModel = function() {
$element.trigger('change');
};
// Observe: Element changes affect Model
$element.on('change', function() {
updateModelFromElement();
});
// Observe: ngModel for changes
$scope.$watch(function() {
return ngModel.$viewValue;
}, function() {
updateElementFromModel();
});
// Initialise BootstrapToggle
$timeout(function() {
$element.bootstrapToggle();
});
}
};
});

How to append row to ngrepeated elements in angularjs?

i am having hard time while appending elements to the ng-repeat elements. Here is the fiddle link
http://jsfiddle.net/ukgym9f9/4/
app.directive("addAgendaRow", function($compile){
return{
restrict: 'A',
link: function(scope, element,attrs,controller){
element.on("click", function() {
console.log("clicked on add row");
$compile(element.parent().parent().parent().append('<tr class="add-remove-row" title="title"><td><div class="has-placeholder" placeholder="Your text Goes Here" contenteditable="true"></div></td><td class="add-remove-row"> </td></tr>'))(scope);
});
}
}
});
When i click on '+', it will remove the existing rows and creates new row. How do i combat this issue ?
Thanks in advance..
There is no need to $compile this when the click event occurs. Just try .closest() to bubble up the DOM tree and append it e.g. to the <table>:
app.directive("addAgendaRow", function() {
return {
restrict: 'A',
link: function(scope, element, attrs, controller) {
element.on("click", function() {
element.closest("table").append('<tr class="add-remove-row" title="title"><td><div class="has-placeholder" placeholder="Your text Goes Here" contenteditable="true"></div></td><td class="add-remove-row"> </td></tr>');
});
}
}
});

ngModelController $modelValue is empty on directive startup

I have an attribute directive that I use on an input=text tag like this:
<input type="text" ng-model="helo" my-directive />
On my directive I'm trying to use the ngModelController to save the initial value of my input, in this case the value of the ng-model associated with it.
The directive is like this:
app.directive('myDirective', function () {
return {
restrict: "A",
scope: {
},
require: "ngModel",
link: function (scope, elm, attr, ngModel) {
console.log("hi");
console.log(ngModel.$modelValue);
console.log(ngModel.$viewValue);
console.log(elm.val());
}
}
});
The problem is that ngModel.$modelValue is empty maybe because at the time the directive is initialized the ngModel wasn't yet updated with the correct value. So, how can I store on my directive the first value that is set on my input field?
How to correctly access ngModel.$modelValue so that it has the correct value?
I'll also appreciate an explanation on why this isn't working as I'm not clearly understanding this from reading the docs.
Plunkr full example: http://plnkr.co/edit/QgRieF
Use $watch in myDirective
app.directive('myDirective', function () {
return {
restrict: "A",
scope: {
},
require: "ngModel",
link: function (scope, elm, attr, ngModel) {
var unwatch = scope.$watch(function(){
return ngModel.$viewValue;
}, function(value){
if(value){
console.log("hi");
console.log(ngModel.$modelValue);
console.log(ngModel.$viewValue);
console.log(elm.val());
unwatch();
}
});
}
}
});
For Demo See This Link

How to update value of ng-model with the expression in html part

Why value of the ng-model is not updated with the expression. Before ng-model is defined value get updated
Value will be updated as soon as phase2 or phase3 changes
<input type="text" name="phase1" value="{{phase2 - phase3}}" ></input>
Value will not be updated
<input type="text" name="phase1" value="{{phase2 - phase3}}" ng-model="phase1"></input>
So I think of writing a directive which will evaluate the expression inside the directive and updated the output to model,
Here is html it will look like
<input type="text" name="phase1" ng-model="phase1" my-value="{{phase2 - phase3}}" my-model-value></input>
Directive:
myApp.directive('myModelValue', function(){
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel',
value: '#myValue'
},
link: function (scope, element, attr, controller) {
scope.model = scope.value;
}
};
});
This directive evaluate only at load time, but I want to continuously update/watch as the dependent fields (phase2 & phase3) changes.
I can update value from controller but I want to do it from html. Please help me, it it possible or against the working of angular
Thanks guys I figure out what I wanted to do. Here is the my final simple but useful directive :)
app.directive('myModelValue', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel'
},
link: function (scope, element, attr, controller) {
attr.$observe('myModelValue', function (finalValue) {
scope.model = finalValue;
});
}
};
});
Usage:
<input type="text" ng-model="phase1" my-model-value="{{phase2 - phase3}}"></input>
<input type="text" ng-model="phase1.name" my-model-value="{{valid angular expression}}"></input>
In order to continously watch the phase2/3 changes you can make use of $scope.$watch function.
Something like this will work for you:
link: function (scope, element, attr, controller) {
scope.$watchCollection('[phase1,phase2]', function() {
//whatever you want to do over here }
and in the scope pass phase1 and phase2 values as well
This will watch the value expression and update the same when value will change
myApp.directive('myModelValue', function(){
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel',
value: '#myValue'
},
link: function (scope, element, attr, controller) {
scope.$watch('value',function(newValue){
console.log(newValue);
});
}
};
});
here value is a local scope so it will watch the expression

Angularjs get form field validity inside directive

I'm hoping this isn't a duplicate - plenty of similar questions about but I can't find an answer that works.
I have an Angular directive, thus:
app.directive('emailInput', function(){
return {
restrict: 'E',
templateUrl: 'template.html',
link: function(scope, elem, attrs, ctrl){
elem.bind('keyup', function(){
// TODO - what?
})
}
}
}
and in the template html:
<input type="email" required ng-model="emailAddress" />
Without knowing the name of the form, inside the link function, I want to know the value of the emailAddress.$valid property - how can I get this?
You can require the formController which would give you access to all of the inputs registered to the form
app.directive('emailInput', function(){
return {
require: '^form', // We look for it on a parent, since it will be defined somewhere higher on the DOM.
restrict: 'E',
templateUrl: 'template.html',
link: function(scope, elem, attrs, ctrl){
elem.bind('keyup', function(){
ctrl.emailAddress.$valid //check validity
})
}
}
}
Remember that Angular keeps track of input elements by name. So you have to give your input a name attribute
<input type="email" required ng-model="emailAddress" name="emailAddress" />
I would also recommend possibly just passing all of this through a directive attribute. You probably don't want to hard code the field names. So you could just have an attribute that takes the validity
inputIsValid='formName.emailAddress.$valid'
And evaluate (or $watch it) in your directive.
We can check validity more easily without knowing the name of input elements.
app.directive('emailInput', function(){
return {
require: '^form', // We look for it on a parent, since it will be defined somewhere higher on the DOM.
restrict: 'E',
templateUrl: 'template.html',
link: function(scope, elem, attrs, ctrl){
elem.bind('keyup', function(){
ctrl.$valid //check validity here
})
}
}
}
This is an old post but for the people who get here by googling, this is the cleanest way to check validity of an input in your directive without knowing its name, so you can use your directive on any input element.
You just need to require the ngModelcontroller:
app.directive('emailInput', function(){
return {
require: 'ngModel'
restrict: 'E',
templateUrl: 'template.html',
link: function(scope, elem, attrs, ngModelCtrl){
elem.bind('keyup', function(){
ngModelCtrl.$valid //check validity
})
}
}
}
See the AngularJS document for ngModel.NgModelController, $valid under the Properties section:
https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
Know it's an old thread but if someone runs into this problem this is how I solved it:
app.directive('emailInput', function(){
return {
restrict: 'E',
templateUrl: 'template.html',
controller:function($scope){
$scope.isInvalid = function(){
return $scope.myelem.data().$ngModelController.$invalid;
}
},
link: function(scope, elem, attrs){
$scope.myelem = $(elem).find("input");
}
}
}
Here is a directive that will set dirty to true even if nothing has been typed in.
By default $dirty is set if something is typed in and wouldn't show a required error message until the user submits. With this
function() {
return function (scope, element, attrs) {
$(element).blur(function () {
scope.$apply(function() {
var field = scope.$eval(attrs.makeDirty);
field.$dirty = true;
});
});
};
HTML:
<label class="fieldLabel" for="confirmEmail">Confirm Email*</label>
<input type="text" id="confirmEmail" name="confirmEmail" ng-model="confirmEmail" ng-pattern="{{Ctrl.Model.Email.EmailAddress}}" required make-dirty="form.confirmEmail">
<span class="error" ng-show="form.confirmEmail.$error.pattern && form.confirmEmail.$dirty">Emails must match</span>
<span class="error" ng-show="form.confirmEmail.$error.required && (form.$submitted || form.confirmEmail.$dirty)">Confirm your email</span>
That allows me to give feedback as the user is filling out or tabbing on the form.
Let me give you another way to do it, it can be useful in some cases
link: function (scope, element, attrs, formCtrl) {
scope.fileSizeError=false;
scope.$watch(function () {
return formCtrl.fileP.$error.maxSize;
},function(newValue) {
scope.fileSizeError=newValue;
});
}
In my case I was inside a directive that is used to upload a file so I needed to know the state of the var $error.maxSize in the template so I did in that way.

Resources