How to verify if a checkbox is checked with jqLite in AngularJs - angularjs

I want to know if a checkbox is checked using jqLite in angularjs. I'm using a directive to check and verify if the value is true or false. I tried this code angular.element('#myCheckbox').val(), but the value returned was false.
<input type="checkbox" id='myCheckbox' my-directive>
angular.js
.directive('myDirective', function(){
return {
restrict: 'A',
link: function(scope, element, attrs) {
console.log(angular.element('#myCheckbox').val());
},
};
})

Related

AngularJs directive change ngModel with delay & model's value don't match

Ng-change is acting weird in a directive. It seems to have a delay in the digest cycle resulting in the wrong (previous) ngModel value in controller immediately after the change.
ngModel : '='
https://codepen.io/anon/pen/moEgdG
What's going on and how to fix?
With the ng-model directive on a component, I recommend using one-way (<) for the input and $setViewValue on the output:
app.directive('newTag', function(){
return {
template: `
<input ng-model="test" ng-change="change(test)"> <br/>
{{test}}
`,
restrict: 'E',
require: "ngModel",
scope: {
ngModel : '<',
},
link: function (scope, elem, attrs, ngModel) {
scope.change = function(val) {
ngModel.$setViewValue(val);
};
},
};
})
Usage:
<new-tag ng-model="tagValue" ng-change("newTagUpdate(tagValue)")>
</new-tag>
For more information, see
AngularJS ngModelController API Reference
AngularJS Developer Guide - Implementing custom form controls (using ngModel)
AngularJS Comprehensive Directive API Reference - require

Angularjs directive to make form dirty without ng-model

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);
});
}
};
})

How to use "required" attribute within Angular directive template?

I'm using an AngularJS directive to generate two radio buttons. I'm hardcoding the "required" attribute into the directive template, but it doesn't behave as expected.
When no radio buttons are checked, it correctly displays this error message, as expected.
<p ng-show="form.$invalid">Error: the form is invalid.</p>
But it doesn't display this error message.
<p ng-show="form.gender.$invalid">Error: the gender input is invalid.</p>
Any idea why?
Please see the Plunker for details:
http://plnkr.co/edit/i5kVeX8WdrUbM83lT6O6?p=preview
You need to tell your directive to validate input fields initially. You can do this by defining $formatters callback checking validity of the fields:
app.directive('dRadio', function() {
return {
require: '^form',
restrict: 'E',
scope: { model: '=ngModel' },
template: '<input required type="radio" id="{{value}}" name="{{name}}" value="{{value}}" ng-model="model"><label for="{{value}}">{{label}}</label>',
link: function(scope, element, attrs, ngModelController) {
scope.name = attrs.name;
scope.value = attrs.value;
scope.label = attrs.label;
ngModelController[attrs.name].$formatters.unshift(function(value) {
ngModelController[attrs.name].$setValidity('required', !!scope.model);
return value;
});
}
};
});
Note, that you also need to add require: '^form' rule.
Demo: http://plnkr.co/edit/rac1RNNOWHs1wTnktJHE?p=preview
You can accomplish by doing this way
Plnkr
I changed the following line
<p ng-show="!test">Error: the gender input is invalid.</p>

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: link function is not being passed a Controller

I am trying to create a directive:
return {
restrict: 'A', // Attribute Directive
ngModel: '^ngModel',
scope: {
'ngModel': '='
},
link: function ($scope: ng.IScope, element, attrs, ctrl) {
var datePickerOptions = {
autoclose: true,
format: attrs.aceDatepickerFormat,
weekStart: attrs.aceDatepickerWeekstart
};
// Attach the datepicker events (must have Bootstrap.DatePicker referenced).
element.datepicker(datePickerOptions).next().on('click', function () {
$(this).prev().focus();
});
element.click(() => {
ctrl.$setViewValue(new Date());
});
}
};
In this example, when the click event occurs on the element, I wish to use ctrl.$setViewValue to the current date (this is a test).
When the link function is called, scope, element and atts are all populated correctly, however the ctrl is null.
The element is with a div with ng-controller set.
<div ng-controller="Controllers.FormElementsController">
<input class="form-control date-picker" id="id-date-picker-1" type="text"
ng-model="DatePickerValue"
ace-datepicker-weekstart="1"
ace-datepicker-format="dd-mm-yyyy"
ace-datepicker="" />
</div>
Why is no controller being passed here?
You have to use require to pull in the controller (ngModelController in your case):
return {
restrict: 'A', // Attribute Directive
require: '^ngModel',
You had it set to ngModel as the property name.
From the docs:
The myPane directive has a require option with value ^myTabs. When a
directive uses this option, $compile will throw an error unless the
specified controller is found. The ^ prefix means that this directive
searches for the controller on its parents (without the ^ prefix, the
directive would look for the controller on just its own element).

Resources