Set initial bootstrap radio button in Angular - angularjs

I found a plunkr courtesy of #user2789093 in question AngularJS: Radio buttons do not work with Bootstrap 3 and modified it some to reflect my issue: http://plnkr.co/edit/sBfSD2?p=info
In angular, I don't think I am supposed to manipulate the DOM, so does anyone have any thoughts on how I could set the intial bootstrap3 radio button to checked without using jquery to check an ID of the inputs?

Once you bind ng-model and set the value attribute correctly, the issue doesn't seem to be the value of the resulting radio button selection. It is only that the bootstrap labels expect an active class to be applied if the selection is made. So you can fix this by adding an ng-class to each selection:
<div class="btn-group col-lg-3" data-toggle="buttons">
<label class="btn btn-default" ng-class="{active: test.currentVal == 'true'}" ng-click="setTransactionDebit('true')">
<input type="radio" value="true" ng-model="test.currentVal"></input>
True
</label>
<label class="btn btn-default" ng-class="{active: test.currentVal == 'false'}" ng-click="setTransactionDebit('false')">
<input type="radio" value="false" ng-model="test.currentVal"></input>
False
</label>
</div>
Here is a working fork of your plunker.

This directive sets the active class on a radio input's parent element when the model value equals the input value, and removes the active class otherwise.
/* Bs radio not setting active class on label because model changes too slowly
* before $render() in bsRadio inside AngularStrap. */
myAppDirectives.directive('bsRadioFix',[function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, controller){
scope.$watch(attrs.ngModel, function(newVal, oldVal){
elem.parent().toggleClass('active', newVal == attrs.value)
})
}
}
}]);

Related

Exclude control from affecting form $pristine

I have a text input within a directive that I want to use as a filter for displaying a list of items, but I don't want the entering of a filter to affect the containing forms $pristine value so that entering a filter doesn't enable the save and show the Reset. How do I do this in angularJS (1.6.x)?
directive template
<form name='myForm'>
<input placeholder="Filter" class='form-control' type='text' ng-model='vm.searchText'>
<ul><li ng-repeat='item in vm.list | filter:vm.searchText'/></ul>
<div>
<br>
<button class='btn btn-primary' ng-click='vm.save()' ng-disabled="myForm.$pristine || frmCrm.$invalid">Save</button>
<div class='pull-right'>
<button class='btn btn-warning' ng-click="vm.reset()" ng-hide="myForm.$pristine">Reset</button>
</div>
</div>
</form>
Yes I know I could easily put the filter input outside the form in this example, but in my actual situation that isn't feasible as I have nested forms and one that wraps basically the whole page.
here's plnkr example:
http://plnkr.co/edit/y1dJLPbyvlZuIW1f7ey9
You can override the $setDirty and $setPristine methods of the ngModel:
angular.module('xyz').directive('dontCheck', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
//set to empty functions
ngModelCtrl.$setPristine = angular.noop;
ngModelCtrl.$setDirty = angular.noop;
}
}
});
I've forked your plunker, you can try the solution:
http://plnkr.co/edit/6UVTQjJtwu4mOXVt7sPT?p=preview
Edit:
Updated plunker to follow your code style. I will leave the code here as is.

Delayed bind on ngModel

I am trying to create a typeahead directive that does not bind the typed text to the model while typing.
This is as such no problem, but I would like to use the ngModel directive for my binding so I am able to use something similar to
<input type="text" ng-model="model.field" typeahead="sourceForTypeahead" />
instead of my current approach which works as a charm
<input type="text" ng-model="tmpFieldForInput" typeahead="sourceForTypeahead" typeahead-model="model.field" />
I can't figure if it is possible to change the "target" of ng-model internally in the directive so I get the typed input, and then is able to set the external model when an result from the source is selected.
Use ngModelOptions to specify when you'd like to bind the input text to the model:
<input type="text" ng-model="myModel" ng-model-options="{ updateOn: 'blur' }">
<p>Hello {{myModel}}!</p>
There are different events you can trigger on, but in this case, the text will only be bound to the model once the end-user leaves focus from the field.
Additional resources: https://docs.angularjs.org/api/ng/directive/ngModelOptions
Like #lux has mentioned, the right way to go about it is to use ng-model-options
But in your case, the ideal solution would be to do wrap your input in a form and bind on submit:
<form name="myForm">
<input type="text" ng-model="myModel" ng-model-options="{ updateOn: 'submit' }">
<p>Hello {{myModel}}!</p>
<input type="submit" value="Submit">
</form>
This will bind the value to the model only when you click your Submit button. This of course can be put anywhere you please.
I found a solution after looking into an old version of the checkbox-list module.
The solution is to change the ngModel attribute on compile time and make it point to an internal property in the directive and then compile in the postlink method.
I have updated the plunker for others to see the prototype: http://plnkr.co/edit/LbHH2pJGX1Iii8ZqqSie?p=preview
(Stack requires me to post code - so here is the )
app.directive('typeahead', ['$parse', '$compile', function ($parse, $compile) {
return {
priority: 1000,
terminal: true,
scope: {
source: '=typeahead',
ngModel: '='
},
compile: function(tElement, tAttrs) {
tElement.removeAttr("typeahead");
tElement.attr("ng-model", "searchTerm");
return function(scope, element, attrs) {
$compile(element)(scope);
// all my logic here

Input field not editable or somehow readonly when using in directive with ion-toggle

Codepen with the problem
this is my directive template:
<ion-toggle class="cw-alerttimebutton" ng-model="targetobject.isEnabled"
ng-checked="targetobject.isEnabled">
<input type="text" ng-model="targetobject.time" value="{{targetobject.time}}"> {{ text }}
</ion-toggle>
this is my app setup:
app.directive('cwAlertTimeButton', function() {
return {
restrict: 'AE',
replace: false, //toggle already replaces
templateUrl: 'templates/directives/cwAlertTimeButton.html',
link: function(scope, elem, attrs) {
scope.targetobject = scope.$eval(attrs.targetobject);
scope.text = attrs.text;
}
};
});
The questions:
<input type="text" ng-model="targetobject.time" value="1980-01-01T11:45:00.000Z"
class="ng-pristine ng-untouched ng-valid">
is write protected nor accessible in this place.
ion-toggle seems to use a class item-toggle that causes problems.
If I move the input outside of the containing element with class item-toggle it works as expected. As well as when I remove the class item-toggle from its parent.
How can I get it to work inside this construct?
The idea is to get an iphone like alarm. E.g. left the time, you click in it, you change it, right you have a toggle to enable disable it.
I use input type=text only to see if it works at all, but it doesn't.
Just in case someone still has this issue. This is caused by the class item-toggle that is generated by ion-toggle. It adds a style pointer-events:none.
To get it editable, overwrite the style for pointer-events of the ion-toggle to pointer-events:all
eg. <ion-toggle ng-model="onOff" ng-change="onChange()" style="pointer-events:all;">.
Of course, you could put this in a style sheet if you prefer. :-)

AngularJS form validation: indicate required fields to user

I would like my form labels to display a red asterisk next to the label when the corresponding form control has a required attribute.
Instead of hard coding the asterisk, I desire a way to append the asterisk to the label dynamically during page load if the label's corresponding input, select or textarea is required (the element the label corresponds to).
I created the directive below, and the directive works. But is there a better, more native way to accomplish my goal? This directive finds all the div.form-group containers and adds a red * character after the label if the corresponding form control inside the div.form-group has a required attribute.
myApp.directive('labelsRequired',function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs){
elem.find('div.form-group').each(function(i, formGroup){
var formControls = $(formGroup).find('input, select, textarea');
console.log(formControls)
if (0 !== formControls.length && undefined !== $(formControls[0]).attr('required')){
jLabel = $(formGroup).find('label');
jLabel.html(jLabel.html()+ "<span class='red-color'>*</span>");
}
})
}
}
});
The directive assumes all inputs, selects, and textareas are inside a div.form-group container.
<div class='form-group'>
<label>First Name</label><!-- this label gets an asterisk -->
<input name='fname' required />
</div>
<div class='form-group'>
<label>Favorite Food</label><!-- this label does not get an asterisk -->
<input name='favFood' />
</div>
You don't need a directive, there are built-in form properties you can use with filters like ng-show, look:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="userForm" novalidate>
<div class='form-group'>
<label>First Name</label>
<input name='fname' ng-model="fname" required />
<label ng-show="userForm.fname.$dirty && userForm.fname.$error.required">* Required field</label>
</div>
<button type="submit">Submit</button>
</form>
</div>
If you define an ng-model for the input you can deal with it looking if it is filled or not. You can also check it only after the user "dirty" it with userForm.fname.$dirty, so the label will be shown only after a user try to input something but then clear it. Try playing with it here JSFiddle
Building off of Corey's answer:
I just used compile rather than link, as I saw that my required attribute was not being applied to my input elements. I also included a select tag for any dropdowns that I had.
app.directive('inputRequired', function () {
return {
restrict: 'A',
compile: function (elem) {
elem.find('label').append("<sup><i class='fa fa-asterisk'></i></sup>");
elem.find('input').attr('required', 'required');
elem.find('select').attr('required', 'required');
}
};
});
If you're not using the built-in Angular validation, you could restructure your directive and attach it to your .form-group element. Like this:
app.directive('inputRequired', function() {
return {
restrict: 'A',
link: function(scope, elem, attr) {
elem.find('label').append('<span>*</span>');
elem.find('input').attr('required', 'required');
}
};
});
Your HTML would then look like:
<div class="form-group" input-required>
<label>Name</label>
<input name="name" />
</div>
<div class="form-group">
<label>Food</label>
<input name="food" />
</div>
However, if you haven't looked into the built-in validation with Angular, I would recommend using it.
This might come too late and it might not be too elegant but it works, if anyone needs it:
<label ng-show="userForm.fname.$validators.hasOwnProperty('required')">* Required field</label>

Angular.js - ng-change not firing when ng-pattern is $invalid

I am using ng-pattern to validate some form fields, and I am using ng-change with it to watch and process any changes, however ng-change (or $scope.$watch) will only fire when the form element is in the $valid state! I'm new to angular, so I don't know how to solve this issue, although I suspect a new directive is the way to go.
How can I get ng-change to fire in both $invalid and $valid form element states, with ng-pattern still setting the form element states as before?
Html:
<div ng-app="test">
<div ng-controller="controller">
<form name="form">
<input type="text" name="textbox" ng-pattern="/^[0-9]+$/" ng-change="change()" ng-model="inputtext"> Changes: {{ changes }}
</form>
<br>
Type in any amount of numbers, and changes should increment.
<br><br>
Now enter anything that isn't a number, and changes will stop incrementing. When the form is in the $invalid state, ng-change doesn't fire.
<br><br>
Now remove all characters that aren't numbers. It will increment like normal again. When the form is in the $valid state, ng-change will fire.
<br><br>
I would like ng-change to fire even when the the form is $invalid.
<br><br>
form.$valid: <font color="red">{{ form.$valid }}</font>
</div>
</div>
Javascript:
angular.module('test', []).controller('controller', function ($scope) {
$scope.changes = 0;
$scope.change = function () {
$scope.changes += 1;
};
});
I have created a working JS Fiddle which shows the problem I am having.
http://jsfiddle.net/JAN3x/1/
By the way, this angular issue also seems to be relevant:
https://github.com/angular/angular.js/issues/1296
You can change the behavior of your input by using ng-model-options.
Just add this attribute to your input and the ng-change event will fire:
ng-model-options="{allowInvalid: true}"
see: https://docs.angularjs.org/api/ng/directive/ngModelOptions
you just need to add
ng-model-options="{ updateOn: 'default' , allowInvalid:'true'}"
this indicates that the model can be set with values that did not validate correctly instead of the default behaviour.
Edit This was answered when ng-model-options was not available. Please see the top-voted answer.
you can write a simple directive to listen input event.
HTML:
<input type="text" name="textbox" ng-pattern="/^[0-9]+$/" watch-change="change()" ng-model="inputtext"> Changes: {{ changes }}
JS:
app.directive('watchChange', function() {
return {
scope: {
onchange: '&watchChange'
},
link: function(scope, element, attrs) {
element.on('input', function() {
scope.$apply(function () {
scope.onchange();
});
});
}
};
});
http://jsfiddle.net/H2EAB/
Inspired by the Li Yin Kong ingenious solution :
His solution has an issue concerning the ndModel update (see the comments of his post).
My fix essentially changes the scope type of the directive. It lets directive access to controller scope (and methods)
Then, watch-change directive does not need an "instruction to eval" (change()) anymore, but only the "name of the controller method to call" (change).
And to get the new value of the input in this function, I pass the context (this = the input itself). So I can get the value or any property of it.
This way, we don't care about ngModel updates (or if the form is invalid, which was another issue of the initial solution : ngModel is deleted if form is invalid)
HTML :
<input type="text" name="textbox" ng-pattern="/^[0-9]+$/" watch-change="change" ng-model="inputtext">
JAVASCRIPT :
app.directive('watchChange', function() {
return {
restrict : 'A',
link: function(scope, element, attrs) {
element.on('input', function(){
scope[attrs.watchChange](this);
})
}
};
});
DEMO : http://jsfiddle.net/msieurtoph/0Ld5p2t4/

Resources