I've been banging my head for a while on this one.
I have a checkbox typed input using ng-model, ng-required, and ng-change
When I uncheck a checkbox I expect the ng-model to be set to false, but it is actually being set to undefined
Also when the ng-required expression toggles; the ng-model also bounces between undefined and false which in turn causes ng-change to trigger.
My actual ng-change code executes some code I do not want to run multiple times.
The simple snippet below shows what I'm running into. I threw a text input into the example to see if it did the same thing. It appears to do the same thing when a user enters a string then deletes it...
This question is not about text inputs...I'm mostly surprised that a false value is not a valid checkbox value when ng-required is true.
var app = angular.module('example', []);
app.controller('controller',['$scope', function($scope){
$scope.inputModel = {
isSelected: undefined,
textInput: undefined
};
$scope.onChangeCounter = 0;
$scope.requiredModel = true;
$scope.resolveCheckboxInput = function() {
if (typeof $scope.inputModel.isSelected === "undefined") {
return "I am undefined"
}
return "I am " + $scope.inputModel.isSelected
};
$scope.resolveTextInput = function() {
if (typeof $scope.inputModel.textInput === "undefined") {
return "I am undefined"
}
return "I am " + $scope.inputModel.textInput
};
$scope.onChangeCallback = function() {
$scope.onChangeCounter++;
};
$scope.isRequired = function() {
return $scope.requiredModel;
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="example">
<ul>
<li> Set Checkbox Input to TRUE</li>
<li> Set Checkbox Input to FALSE</li>
<li> Toggle ng-required</li>
<li> Checkbox Input is cleary affected</li>
</ul>
<div ng-controller="controller">
<label>
<input type="checkbox"
ng-required="isRequired()"
ng-change="onChangeCallback()"
ng-model='inputModel.isSelected' />
Checkbox Input
</label>
<br><br>
<div>
<b>Checkbox Input:</b> {{resolveCheckboxInput()}}
</div>
<br><br>
<label>
<input type="text"
ng-required="isRequired()"
ng-model='inputModel.textInput' />
Text Input
</label>
<br><br>
<div>
<b>Text Input:</b> {{resolveTextInput()}}
</div>
<br><br>
<label>
<input type="checkbox"
ng-model='requiredModel' />
ng-required
</label>
<br><br>
<div>
<b>Checkbox Input ng-change Counter:</b> {{onChangeCounter}}
</div>
</div>
</div>
Credit goes to this SO question/answer: Checkbox input undefined when unchecked - AngularJS
You need to add ng-model-options.
<input type="checkbox"
ng-required="isRequired()"
ng-change="onChangeCallback()"
ng-model='inputModel.isSelected'
ng-model-options="{ allowInvalid: true }" />
I'd usually mark this as duplicate but the answer in the link wasn't accepted, so it may not be apparent that this works.
Related
I'm using Bootstrap radio button groups and am having a hard time getting the selected value into my controller. I have a small snippet of JS to set the selection on which button was clicked:
$(document).ready(function() {
$('form .btn-group label').on('click', function() {
$(this).find('input').prop('checked', true);
});
});
Here is example HTML:
<form name="add-form" ng-submit="addFavorites()" novalidate>
<div class="form-group">
<label class="control-label">Color</label>
<div class="btn-group" data-toggle="buttons">
<label class="btn">
<input type="radio" name="color" value="red" class="form-control" ng-model="favorites.color" ng-required="true">Red
</label>
<label class="btn">
<input type="radio" name="color" value="blue" class="form-control" ng-model="favorites.color" ng-required="true">Blue
</label>
</div>
</div>
</form>
Now when I submit this with ng-submit to this function, I do not get any console logged values for my radio buttons.
$scope.addFavorites = function() {
angular.forEach($scope.favorites, function(value, key) {
console.log(key, value);
});
};
What am I doing wrong?
You do not need this code:
(document).ready(function() {
$('form .btn-group label').on('click', function() {
$(this).find('input').prop('checked', true);
});
});
Your radio button is wrapped with its label so HTML5 will propagate click from the label to the radio.
Initialize your $scope.favorites object to {}
That is it, in submit you can get your $scope.favorites object with all its arguments.
Plunker: http://plnkr.co/edit/OatdIsvCUBSniHHQFyxG?p=preview
In this plunk I have a form with two fields, each validated with ngMessage, where the error message appears when the user tabs out of the field, or the form is submitted.
The issue is that if the message is shown and then hidden (because the problem was fixed) the borders are still shown.
Try tabbing out of a field, then entering a value, you will see only borders in the error message.
How to get rid of these borders?
HTML
<body ng-app="ngMessagesExample" ng-controller="ctl">
<form name="myForm" novalidate ng-submit="submitForm()">
<label>
Enter Aaa:
<input type="text"
name="aaa"
ng-model="aaa"
required ng-blur="aaaBlur()" />
</label>
<div ng-show="showAaa || formSubmitted"
ng-messages="myForm.aaa.$error"
style="color:red;background-color:yellow;border:1px solid brown">
<div ng-message="required">You did not enter a field</div>
</div>
<br/>
<label>
Enter Bbb:
<input type="text"
name="bbb"
ng-model="bbb"
ng-minlength="2"
ng-maxlength="5"
required ng-blur="bbbBlur()" />
</label>
<br/><br/>
<div ng-show="showBbb || formSubmitted" ng-messages="myForm.bbb.$error"
style="color:red;background-color:yellow;border:1px solid brown">
<div ng-message="required">You did not enter a field</div>
</div>
<br/>
<button style="float:left" type="submit">Submit</button>
</form>
</body>
Javascript
var app = angular.module('ngMessagesExample', ['ngMessages']);
app.controller('ctl', function ($scope) {
$scope.formSubmitted = false;
$scope.showAaa = false;
$scope.showBbb = false;
$scope.submitForm = function() {
$scope.formSubmitted = true;
};
$scope.aaaBlur = function() {
$scope.showAaa = true;
};
$scope.bbbBlur = function() {
$scope.showBbb = true;
};
});
It's because you show the div (showAaa=true) but there's no content. Solution? Don't show the div. :)
<div ng-show="!myForm.aaa.$valid && (showAaa || formSubmitted)"
In which field do you have the problem ? Both or only the 2nd one ?
I see that in the 2nd field you fixed a min and max length. If they're not right, you don't have any ng-message to handle them, but your field will be in error, so you'll end up with the red border and no message.
By the way : you can use [formName].[fieldName].$touched instead of using your native onblur.
I'm trying to build a directive for my Angular to help with the integration of form fields. I've implemented Scott Allens solution from his Angular playbook, and it works fine for a normal stacked form.
I need however to adapt it to a horizontal form instead. Here's my code:
Markup
<div form-group>
<label for="name">Name</label>
<input type="text" id="name" ng-model="vm.name">
</div>
formGroup directive
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
var label = element.querySelector("label");
label.classList.add("control-label");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
}
element.classList.add("form-group");
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
The output becomes:
<div form-group="" class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" id="name" ng-model="vm.name" class="form-control">
</div>
And that's fine for stacked form. Since I need a horizontal form, my output needs to look like this:
<div form-group="" class="form-group">
<label for="name" class="control-label col-sm-3">Name</label>
<div class="col-sm-9">
<input type="text" id="name" ng-model="vm.name" class="form-control">
</div>
</div>
I've tried many solutions and I can get it work with single elements like an input, textarea or a select. It becomes much more tricky when I have something like two radio buttons inside my markup like this:
<div form-group>
<label>Active</label>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active"> No
</label>
</div>
</div>
The desired output of the above mentioned code should be:
<div form-group class="form-group">
<label class="control-label col-sm-3">Active</label>
<div class="col-sm-9">
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active"> No
</label>
</div>
</div>
</div>
Please notice that the input(s) in the form-group is not fixed. It can be either a single input, textarea, select, a group of radio buttons or checkboxes. I'm lost for how I can make that happen. Any help is appreciated. Thanks!
UPDATE
I made some small changes to Mark Veenstra's code to make it (sort of) working:
function setupDom(element) {
element.classList.add("form-group");
var label = element.querySelector("label");
label.classList.add("control-label", "col-sm-3");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
angular.element(input).wrap(angular.element('<div class="col-sm-9"></div>'));
}
var div_radio = element.querySelector("div[class='radio']");
angular.element(div_radio).wrap(angular.element('<div class="col-sm-9"></div>'));
}
This does not work completely as intended with multiple radio inputs since it only wraps the <div> on the first radio input element.
The output from radio button example in my original post using Marks code is:
<div form-group="" class="form-group">
<label class="control-label col-sm-3">Active</label>
<div class="col-sm-9">
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active" value="true"> Yes
</label>
</div>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active" value="false"> No
</label>
</div>
</div>
SOLUTION
Check out the Plunker with the final result: http://plnkr.co/edit/Wv6V86hHTCz3URS9DhdU?p=preview
In the angular.element documentation you can find the method wrap() to be able to wrap HTML around a selected element. Or see this direct link.
So what you could do in your directive is change the setupDom() function to match your requirements per type of form element.
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
element.classList.add("form-group");
var label = element.querySelector("label");
label.classList.add("control-label col-sm-3");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
input.wrap(angular.element('<div class="col-sm-9"></div>'));
}
var div_radio = element.querySelectorAll("div[class='radio']");
div_radio.wrap(angular.element('<div class="col-sm-9"></div>'));
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
NOTE: This code is not tested, maybe there are some minor mistakes, but I guess you'll get the point now.
Mark's suggestion came close, but it didn't solve my problem completely. I ended up using the following code in my formGroup directive:
(function (module) {
"use strict";
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
element.classList.add("form-group");
var children = angular.element(element).children();
var labels = children.splice(0, 1);
// Set label classes
labels[0].classList.add("control-label", "col-sm-3");
// Wrap children in div
angular.element(children).wrapAll(angular.element("<div class='col-sm-9'></div>"));
// Handle inputs
var inputs = element.querySelectorAll("input, textarea, select");
for (var i = 0, len = inputs.length; i < len; i++) {
var input = inputs[i],
type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox") {
input.classList.add("form-control");
}
}
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
module.directive("formGroup", formGroup);
}(angular.module("app.core")));
Check out this Plunker to see it in action: http://plnkr.co/edit/Wv6V86hHTCz3URS9DhdU?p=preview
I am trying to append an element to the DOM from user text input using AngularJS.
The desired behaviour is:
User types string into input ng-model "newTask"
Presses enter key
Dynamic element is then appended to the DOM
The relevant section of HTML is as follows:
<div class="add-task">
<input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>
<div class="task-list">
<a class="task"><span class="text">{{ newTask }}</span></a>
</div>
Currently the HTML is instantly updated. How can I bind this event to only happen after enter keypress? The AngularJS UI is also loaded.
Many appreciations,
an AngularJS newbie
Try creating a temp value
Html:
<input type="text" placeholder="Type then press enter to create task" ng-model="tmpTask" ng-keypress="saveTask($event)" />
Your ng-model binds to a tmpTask property. Only when enter is pressed, save it back to newTask
JS:
app.controller('MainCtrl', function($scope) {
$scope.saveTask = function (event){
if (event.keyCode == 13){
$scope.newTask = $scope.tmpTask;
}
}
});
DEMO
html
<form ng-submit="createTask()">
<input type="text" ng-model="newTaskText" />
</form>
<div ng-repeat="task in tasks">{{ task.text }}</div>
controller
$scope.tasks = [];
$scope.createTask = function() {
$scope.tasks.push({
text: $scope.newTaskText
});
};
Since one of the other answers addresses the ng-keypress, I'll offer up the fact you don't need to use the ng-keypress event but can just watch the variable instead which negates the need for enter:
http://plnkr.co/edit/osFGRtpHG46bMyp15mc8?p=preview
app.controller('MainCtrl', function($scope) {
$scope.taskList = [];
$scope.$watch('newTask', function(newVal){
if (newVal=="newTask") {
$scope.taskList.push("Task " + $scope.taskList.length);
$scope.newTask = null;
}
});
});
<body ng-controller="MainCtrl">
<div class="add-task">
<input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>
{{taskList.length}}
<div class="task-list" >
<a class="task" ng-repeat="task in taskList" ><span class="text">{{ task }} </span></a>
</div>
</body>
HTML:
<ul>
<li><a><i class="icon-white icon-save"></i></a></li>
</ul>
<form>
<input type="text" value="{{ selectedUser.firstname }}" ng-model="selectedUser.firstname">
<input type="text" value="{{ selectedUser.lastname }}" ng-model="selectedUser.lastname">
</form>
I am dealing with user objects fetched from my REST API. So basically there is a list of users. On click the above form is revealed.
function UserController($scope, User){
$scope.users = User.query();
$scope.selectedUser = null;
$scope.select = function(user){
$scope.selectedUser = user;
}
}
I want to display the save link only when form values have changed. Any ideas how to do this with angular.js?
Give your form a name, such as:
<form name="dataForm">
<input type="text" name="firstname" ng-model="data.firstname" />
<input type="text" name="lastname" ng-model="data.lastname" />
</form>
The form will now be a named model in your scope and you can hide/show the save button based on whether the form is pristine:
<ul ng-hide="dataForm.$pristine">
<li><a><i class="icon-white icon-save"></i></a></li>
</ul>
This approach has the advantage of showing the save button if you change any of the form elements inside the form and the drawback of not checking the input values against their original values, just the fact that they have been edited.
Here is an example of showing your element only when both fields have data:
<div ng-controller="TestCtrl" ng-app>
<ul ng-show="enableSave(data)">
<li><a><i class="icon-white icon-save"></i></a></li>
</ul>
<form>
<input type="text" name="firstname" ng-model="data.firstname" />
<input type="text" name="lastname" ng-model="data.lastname" />
</form>
</div>
And here is your controller:
function TestCtrl($scope) {
$scope.data = {firstname: "", lastname: ""};
$scope.enableSave = function(data) {
return data.firstname.length > 1 && data.lastname.length > 1;
};
}
You can put any logic you want into enableSave. I've chosen to require that they both have at least two characters... you can do whatever you need.
Here is a jsFiddle that illustrates it: http://jsfiddle.net/nDCXY/1/
EDIT by OP: my solutions
$scope.enableSave = function(user) {
if(!angular.equals(user, oldUser)){
return true
}else{
return false;
}
};