We have a mover directive with 2 lists controls and 4 buttons. I want to be able to add keepPristine property to this directive and if I set it to true, the control should not react on changes and set ng-dirty flag. I tried adding to the ng-change event of the list:
$scope.onChanged = function (assigned) {
$scope.selectedItem = assigned[0];
if ($scope.keepPristine)
{
$scope.form.assignedList.$pristine = true;
$scope.form.unAssignedList.$pristine = true;
}
}
Unfortunately, when I inspect this control using Developer's Tools I see it's still has ng-dirty state. What should I do to make sure both lists are always in the pristine state regardless on my interaction with them?
You should try to use the method $setPristine() instead... and, if after that, it's not "pristine" yet then add an $scope.$apply() after the $setPristine() call.
Related
I am struggling to figure out a way to trigger these AngularJS classes on a form I am trying to automatically fill with a chrome extension I am making. The form (specifically a textbox) has to be validated/modified before it will be validated and therefore submitted.
I originally tried using javascript to set the value of the textbox using the value property. This did not validate the form. I then tried using a dispatch event to send a key to the textbox, which resulted in nothing being input into the text box. How can I validate the form without requiring human input, or is this not possible?
Clarification, I am trying to replicate this action without user input by using a chrome extension.
Reference https://www.w3schools.com/angular/angular_validation.asp
Sounds like you need to create some events to simulate whatever angular is listening for, probably change or blur. Here's an example using click from mozilla:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events
function simulateClick() {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
var cb = document.getElementById('checkbox');
var cancelled = !cb.dispatchEvent(event);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
}
How can I validate the form without requiring human input
Get the forms controls:
var controls = $scope.tdForm.$getControls();
Trigger their validators:
controls.forEach( _ => _.$validate() );
From the Docs:
$validate();
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
For more information, see
AngularJS Form Controller API Reference
AngularJS ngModelController API Reference
When you type into the form, it updates the state of its controls (touched, dirty, etc.). According to how you define your fields validators (required, minLength...) the form will be valid or not after the user input.
In your submit method you should not proceed if any form fields are not valid. See AngularJS Developer Guide — Forms or Scotch Tutorials — AngularJS Form Validation you can have more details about AngularJS validation.
As Mike mentioned, you can use ngClass conditionally (see below) to apply some style classes only if a boolean condition occurr, for example the form is not valid.
<div ng-controller="ExampleController">
<form name="form" novalidate class="css-form">
<input type="text" ng-model="user.name" name="username" ng-class="{ 'error': !isValid }"/>
<div ng-show="form.$submitted>
<span ng-show="form.username.$error">Wrong Name</span></span>
</div>
<button ng-click="submit(user)"> Submit </button>
</form>
</div>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.isValid = true;
$scope.submit= function(user) {
if (user.name != 'Carl') {
$scope.isValid = false;
}
};
}]);
You can always programmatically change the form states if needed. For example to set the field to pristine:
$scope.form.$setPristine();
$scope.form.$setUntouched();
$setPristine sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class.
Additionally, it sets the $submitted state to false. This method will also propagate to all the controls contained in this form.
$setUntouched sets the form to its untouched state. This method can be called to remove the 'ng-touched' class and set the form controls to their untouched state (ng-untouched class).
Setting a form controls back to their untouched state is often useful when setting the form back to its pristine state.
UPDATE
Now it is clear what you are attempting to achieve. The two methods above can be used to set the form state, but if you want to validate it from code (this can be done passing the form to a service or directly in the controller for instance) then $validate() method will allow you to achieve that as mentioned by George.
I'm working with Angular material 1.0.5 and the md-checkbox directive.
I was wondering if anyone knows how to make this into a tri-state checkbox.
The three states (and the associated variable values for my situation) are:
Checked (true)
Unchecked (false)
Indeterminate (null)
For the version of Angular Material specified (1.0.5), when the checkbox is disabled, it
shows the indeterminate state as a checkbox with a question mark in it.
However, when it is not disabled, it defaults back to a two state checkbox.
So far my failed attempts have been to wrapping the directive in another directive and trying to take over control of the md-checkbox.
Does anyone have any pointers in this situation?
Thanks.
If you use angular material >1.0.8, you are able to use the md-indeterminate attribute and manage the value with your own ng-change function.
HTML
<md-checkbox ng-model="vm.checkModel"
md-indeterminate="vm.checkModel === null"
ng-change="vm.checkModelChange()">
Checkbox
</md-checkbox>
CONTROLLER
var checkValues = [false, true, null];
var index = 0;
vm.checkModel = checkValues[index];
vm.checkModelChange = function() {
vm.checkModel = checkValues[++index % checkValues.length];
}
Check this JSFIDDLE for angular material >1.0.8. (Best solution)
Check this JSFIDDLE for angular material 1.0.5. (I've used ng-class css to simulate the indeterminate state).
I have a simple Kendo ComboBox:
HTML:
<div>
<h5>Brand</h5>
<div id="combo1"></div>
</div>
JavaScript:
j$("#combo1").kendoComboBox({
dataTextField: "name",
dataValueField: "id",
value: "Original_Brand_Value",
dataSource: {
transport: {
read: {
url: "..."
}
}
}
});
Note that the ComboBox has a default initial value of "Original_Brand_Value". How do I check if the Kendo ComboBox is "dirty" i.e. currently has a value other than "Original_Brand_Value"? Seems like I should be able to do something like:
j$("#combo1").data("kendoComboBox").isChanged()
**OR**
j$("#combo1").data("kendoComboBox").dataSource.isChanged()
But I have searched far and wide and there seems to be no such method. There has to be some way to do this, this must be a common use case.
As you have concluded, the kendoComboBox widget itself does not track whether it has been changed state. The datasource does have a hasChanges() method but making a selection does not change the datasource, it just gets a different value from it. However the kendoComboBox does raise events that you can use, for example 'select' that is fired when the user makes a selection: http://docs.telerik.com/kendo-ui/api/javascript/ui/combobox#events-select
For example you could add this to your comboBox configuration:
select: function(e) {
var item = e.item; //jQuery object representing the selection
isDirty = true; //Set a flag or call a function as required. Perhaps check the item as well to make sure it isn't the default value.
}
Alternatively there is also a method called 'select' that can be used to get or set the selected item. You can use this to get the selected index (if it is not zero, then the comboBox has a non-default selection):
var selectedIndex = j$("#combo1").data("kendoComboBox").select();
This isn't the only way. If you were to use MVVM declarative syntax with the comboBox bound to a property on a kendo.Data.Model (which is observable), any changes will automatically set the dirty flag on that model: http://docs.telerik.com/kendo-ui/api/javascript/data/model#fields-dirty
MVVM is a very powerful design pattern to use with kendo but I think going into more detail is outside the scope of what you're asking.
You can use the value() method to check the current widget value and compare it to the initial value, but probably this approach is not appropriate, as it is too obvious.
http://docs.telerik.com/kendo-ui/api/javascript/ui/combobox#methods-value
Another possible option is to subscribe to the change event of the widget and raise a custom dirty flag in a JavaScript variable. You could even set an expando on the ComboBox widget object.
http://docs.telerik.com/kendo-ui/api/javascript/ui/combobox#events-change
On a side note, the ComboBox is an input widget that should hold and submit a form value. That's why it should be created from an input or select element, not from a div.
I am new to Angular JS. When the user check/uncheck on a check box, I am calling a function in a controller using ng-click. I am passing $event to the function in controller. Using the $event, I am able to get the srcElement inside the controller function. Now I would like to set the previous check/uncheck value to the check box based on certain conditions.
$scope.isAccessChanged = function(event){
if (some condition) {
var elem = angular.element(event.srcElement);
/** here how to set the elem value back to whatever it was before.*/
}
};
Lets say you have check box like
<input ng-model="form.isSelected" type="checkbox">
All you need to do is:
$scope.form.isSelected = !$scope.form.isSelected;
Avoid DOM manipulation and limit jQuery use as much as possible in angular.
I recommend using jQuery only in directives to make it less of an available option.
Try this out:
<input type="checkbox" ng-model="foShizzle" ng-click="isAccessChanged()"/>
$scope.isAccessChanged = function(event){
if(some condition){
$scope.foShizzle = !$scope.foShizzle; // This will reverse the user's decision
}
}
See edit at the bottom.
My company has a huge code base and we want to start using knockout more effectively. However, we have validation code in place already that takes care of all aspects of client-side validation. It uses jQuery to show validation error messages and to sanitize user input.
For example, if I add the class "validate-range" to an input, it will use jQuery change/focusout events to track changes and then if a value is out of the range, it will replace it with the min/max value using $(input).val(). Since this validation code makes changes this way programmatically, my knockout view model won't be updated when these kind of changes are made.
This validation code is used everywhere in the system, and can't be replaced at the moment, so in order to use knockout, I have to make it work along side this code. What i've tried so far is creating a custom value binding that adds an additional change event handler which is used to update the view model whenever the validation code changes an input's value.
This works surprisingly well in all cases except inside a foreach binding (which is the same as using the template/with binding I would imagine). My change event handler isn't being fired on any inputs inside the foreach that use the custom value binding, even though the custom binding is being reapplied to all inputs inside the foreach every time the observable array changes.
I was hoping someone has dealt with this problem before, having to make knockout work with existing javascript code that changes DOM values, and thus doesn't update the view model. Any help is greatly appreciated.
Javascript code for custom binding, creating view model, and old validation code:
// custom value binding for amounts
ko.bindingHandlers.amountValue = {
init: function (element, valueAccessor) {
var underlyingObservable = valueAccessor(),
interceptor = ko.computed({
read: function () {
var value = underlyingObservable();
return formatAmount(value);
},
write: function (newValue) {
var current = underlyingObservable(),
valueToWrite = parseAmount(newValue);
if (valueToWrite !== current)
underlyingObservable(valueToWrite);
else if (newValue !== current.toString())
underlyingObservable.valueHasMutated();
}
});
// i apply a change event handler when applying the bindings which calls the write function of the interceptor.
// the intention is to have the change handler be called anytime the old validation code changes an input box's value via
// $(input).val("new value"); In the case of the foreach binding, whenever the observable array changes, and the table rows
// are re-rendered, this code does get ran when re-applying the bindings, however the change handler doesn't get called when values are changed.
ko.applyBindingsToNode(element, { value: interceptor, event: { change: function () { interceptor($(element).val()); } } });
}
};
// view model creation
// auto create ko view model from json sent from server
$(function () {
viewModel = ko.mapping.fromJS(jsonModel);
ko.applyBindings(viewModel);
});
// old validation code
$(document).on("focusout", ".validate-range", function () {
var $element = $(this),
val = $element.val(),
min = $element.attr("data-val-range-min"),
max = $element.attr("data-val-range-max");
if (val < min)
// my change handler from custom binding doesn't fire after this to update view model
$element.val(min);
if (val > max)
// my change handler from custom binding doesn't fire after this to update view model
$element.val(max);
// more code to show error message
});
HTML code that uses the custom binding inside of a foreach binding:
<table>
<thead>
<tr>
<td>Payment Amount</td>
</tr>
</thead>
<tbody data-bind="foreach: Payments">
<tr>
<td><input type="text" class="validate-range" data-val-range-min="0" data-val-range-max="9999999" data-bind="amountValue: Amount" /></td>
</tr>
</tbody>
</table>
So in the above example, if I enter "-155" in an amount text box, my custom binding runs and sets the view model Amount to -155. Then the old validation runs and re-sets the value of the textbox to "0" with $(input).val(0). My view model doesn't get updated at this point, and still reflects the -155 value. My change event handler from the custom binding is supposed to be ran to update the view model to 0, but it doesn't.
Edit:
As pointed out in the answer, .val() does not trigger any change events. The change event handler I added didn't do anything. The reason the view model was being updated when the validation code changed a value outside of the foreach binding was because we had logic somewhere else in our javascript code that was manually triggering the change event using the blur event, which in turn triggered my custom binding to run and update the view model. This blur event handler was directly bound to the text boxes, instead of being delegated, so it worked for text boxes that were there when the page is first rendered, but not for the ones dynamically inserted by the foreach binding.
For now, I just changed this logic to delegate the events within the document, so it would include dynamically inserted text boxes, and it seems to be working fine. I'm hoping to come up with a better solution in the future.
Calling $(element).val("some value"); does not trigger the change event.
You would need to do: $(element).val("some value").change();