I'm trying to use Angularjs's built in form validation, but when I add a required field to a checkbox to make sure its checked I get odd results. If I do the opposite of the value I'd like it seems to work fine. The following fiddle will explain it more thoroughly.
This fiddle works great when you're using Angularjs 1.0.4, but if you switch Angular to 1.2.1 it breaks all over the place. Is there a new way of doing this now? or would this be considered a bug?
EDIT
I simplified the code to make it make more sense, check out this fiddle. The key problem here is that it's doing the opposite of what I would like it to do, but if I switch it the entire thing falls apart. I've also replaced the older code I had here with the newer fiddle. You can still see the older fiddle code in the above link.
Here is the html:
<div ng-controller="myCtrl">
<ng-form name="myForm">
<input type="checkbox" ng-model="value.checkbox" name="group-one" ng-true-value="1" ng-false-value="0" ng-required="value.checkbox==1" />
<input type="submit" value="Send" ng-disabled="myForm.$invalid" />
{{choice}}
</ng-form>
</div>
Here is the controller:
function myCtrl($scope) {
$scope.value = {"checkbox":""};
}
This appears the be a bug, though I'm not sure it's the same as your original problem. The required directive is not functioning properly when an ng-true-value is specified.
Found an existing bug report.
If you use ng-click, you should pass $event in and then get the choice from $event. Or you can use ng-checked to get the value directly.
ng-click="updateQuestionValue($event)"
$scope.updateQuestionValue = function($event){
var choice = $event.target;
//...
}
Related
I was trying to create a custom validator for angular-formly repeated section.
The form should be valid only if the sum of the percentage inputs is 100. So for example if repeat section has 2 fields 50 and 50 should be a valid option or 25 and 75 and so on.
While I was working on a JSbin in order to do that I found out that the repeated model is not actually updated onKeydown. Therefore iterating though all the repeat section values and calculating their sum is not possible.
I also tried with modelOptions: { updateOn: 'Keydown' } with no success. It actually makes the validator not to get called at all.
UPDATE
I came up with the following solution from the matching fields example.
Unfortunately it appears that the example its self has a problem.
Play with the following JSbin and see that there are many cases where the validator gets called and returns true but the field/fields still remain red (indicating they have a problem).
Here is the JSBin.
Apologies since I didn't had the time to get back on this one. It has an open issue on GitHub for 2 months now. I fixed it temporary by using 7.1.2 version of angular-formly and just waiting for an update. The updated version of JSBin I have on the question should be working.
UPDATE
Since I had time and fixed this with repeat section (with a hacky way of course) I tough I should post it in case someone else is looking for this.
(note: the solution doesn't depend on formly version)
Working JSBin
You made a typo while using modelOptions: { updateOn: 'Keydown' } the Keydown's k should be small case instead of uppercase, after fixing typo its working as expected. Also the ngModelOptions accept all event name in small case like keydown, keyup, blur, focus, etc.
modelOptions: { updateOn: 'keydown' }
Forked Plunkr
To create your own checks is best used reusable components, for example directive use-form-error.
Look at the example of jsfiddle.
<div ng-form="testForm" use-form-error="sumNot100" use-error-expression="input_1+input_2+input_3!=100">
<label>Sum of all input must be 100</label>
<br>
<label>Input 1</label>
<input ng-model="input_1" type="number" name="input_1">
<label>Input 2</label>
<input ng-model="input_2" type="number" name="input_2">
<label>Input 3</label>
<input ng-model="input_3" type="number" name="input_3">
<div ng-messages="testForm.$error" class="errors">
<div ng-message="sumNot100">
Sum of all input not equal 100
</div>
</div>
<button ng-disabled="testForm.$invalid">
Submit
</button>
</div>
I use angular and the bootstrap-switch plugin in my application. It works like this:
<input type="checkbox" name="my-checkbox" checked>
<script>$("[name='my-checkbox']").bootstrapSwitch("size", "small");</script>
The problem is that if I want to use all the attributes I found there it doesn't work.
How can I use ng-model with my switch?
I would like to use it like this:
<input type="checkbox" name="my-checkbox" checked="variableStatus" data-on-color="success" data-off-color="warning">
or
<input type="checkbox" name="my-checkbox" ng-model="variableStatus" data-on-color="success" data-off-color="warning">
The most obvious reason that it's not working is that bootstrap-switch is a jQuery library. Angular doesn't play well with jQuery, so if you want to use it, you'll have to write your own directive. However, the following link will give you a directive someone wrote called angular-bootstrap-switch. You might want to check it out.
https://github.com/frapontillo/angular-bootstrap-switch
Bootstrap has special method for starting, if you want start it, try it start after period time in angularjs.
setTimeout(installSwitcher, 1000);
function installSwitcher(){
$("[name='my-checkbox']").bootstrapSwitch();
}
<input type="checkbox" name="my-checkbox" checked>
if(currentAdmin.target =='new')
{
$('#btnDel').hide();
//Not working !!!
$('#inputPassword1').attr("ng-required","true");
$('#inputPassword2').attr("ng-required","true");
}
else
{
$('#btnDel').show();
$('#inputPassword1').attr("ng-required","true");
$('#inputPassword2').attr("ng-required","true");
}
Well, basically I want to place the ng-required based on the condition. I made a trial using the required (without ng) and it does not works as well.
I inspected the element and injected the required and ng-required into the html and it's not works.
This will always be ignored after rendered. I need to do such thing like "Validator, refresh because it's different now"
any clue ?
Even though I myself hate the kind of answer I am about to give, I feel it is appropriate in this situation: This is not the way to write if using angular...
So what should you do?
place the ng-required in the html code and set the value of the attribute to a bound variable that you set depending on your condition.
Example:
index.html
<form ng-controller="formController">
<input type="password" ng-required="isAdmin">
<input type="password" ng-required="!isAdmin">
</form>
app.js
angular.module('app',[]).controller('formController', function($scope){
$scope.isAdmin=false;
if(currentAdmin.target == 'new'){
$scope.isAdmin=true;
}
});
Not complete code, but hopefully you still understand what I mean.
I'm trying to use the Switch component from Zurb's Foundation.
It works great until you put it inside an ng-repeat. Then, all the switches except the last one are broken--they don't display the labels until you click them.
Here's a JSBin documenting the issue. Anyone know what's up?
You need ng-model on your radios. It works fine in your JSBin if you include an ng-model on each radio button.
According to the docs, value is also required.
Edit:
Okay look at this version, I finally got it to work with both ng-model and ng-value, which I've learned is preferable to value. What do you think, does that work for you?
Apparently ng-repeat created a child scope for each iteration. Using $parent seems to be a way around that.
Found I had to use "ng-checked" in the following fashion for it to work as expected within an "ng-repeat". As long as the ng-clicked var is unique per switch, should work as expected. Make the toggle function something that toggles the visible value between true and false.
<div class="switch" ng-click="toggle()">
<input type="radio" ng-checked="!visible">
<label>Off</label>
<input type="radio" ng-checked="visible">
<label>On</label>
<span></span>
</div>
Hope that helps someone.
I have a very simple form where a radio button is required to be selected in order for a form to be valid. The radio buttons are generated by ngRepeat.
As you can see from this fiddle, while the desired behavior is that when the radio button is clicked for the first time, that should validate the form (being the only element), however notice that it takes an additional click (on the same radio button or any other) to validate the form:
http://jsfiddle.net/Xsk5X/3/
What am I missing?
All the other solutions are work-arounds: All you have to do is remove the name attribute, when you use the ng-model attribute you don't need it and they conflict.
Specifying the name causes Angular to get confused because it changes the value once for the angular model and another time for the form element name.
I had this problem because a colleague had copied the radio buttons in the same page and hidden them for temporary reference, so duplicate radio inputs with the same name
Try adding the ng-click attribute to your radio button input.
Credit to Manny D for noting this first. Yes, this is a little hackish, but it works. E.g.,
<input type="radio"
name="groupName"
ng-model="editObject.Property"
ng-value="someValue"
ng-click />
The reason why this is breaking - is because you're setting all radio boxes to be required. As a result, depending on how you write it - angularjs is saying it's invalid because not all have been selected at some point.
The way around this is to do something like the following:
Using checkboxes and required with AngularJS
(check the 1st and 2nd answers). This will resolve your problem.
Seems like an AngularJS 1.0.3 $scope.$apply update problem.
Tested your exact Fiddle in 1.0.2 (check it out yourself) and it works the way you expect it too.
It doesn't seem like there's anything wrong with your code, just that $scope.$apply(or $digest) isn't working as expected on the first select.
A very simple fix is to force the $scope to also update on every select, try changing the following line of code in your form:
<p>Favorite Beatle</p>
change it too:
<p>Favorite Beatle: {{name}}</p>
And you will see how myForm.$invalid is updated even after the first click.
I would try it out with the latest AngularJs version and let us know if that happens there too.
Another solution I can think of it setting the default selected radio, which will cause myForm.$invalid to be false from the beginning. you can do this by adding the following line in your controller code:
$scope.name = "John";
or any default name you want.
Some times the $digest cycle dosen't $apply(fn) because you have two o more instances.
For fix this you need $apply this trick manually, so put this in your directives:
angular.('myApp',[])
.directive('ngRadioExtend', ['$rootScope', function($rootScope){
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, iElm, iAttrs, controller) {
iElm.bind('click', function(){
$rootScope.$$phase || $rootScope.$apply()
});
}
};
}])
and use it as:
<input type="radio" name="input_name" ng-model="some" value="F" ng-required="true" ng-radio-extend>
<input type="radio" name="input_name" ng-model="some" value="M" ng-required="true" ng-radio-extend>
DONE it's the correct way!
The problem of the scope not getting updated still occurs in 1.1.5
A simple work around is to just add
<span ng-show="false"> {{name}} </span>
Fiddle: http://jsfiddle.net/jonyschak/xaQJH/
For IONIC v1,
add name="" to prevent ionic auto-generate attribute name.
Then, I can change the selected item with only one click.
<ion-radio class="label-ticket"
ng-repeat="topic in vm.listTopic track by $index"
ng-value="topic"
ng-model="vm.topicSupport"
name="">
{{ topic.title }}
</ion-radio>