I have check boxes in my application. I put it inside directive. Now the problem is I want to unchecked any of checked boxes from controller. I am able to unchecked all checkboxes but not particular one. Is there any way to tell the directive to unchecked the checkbox by setting model value to false.
DIRECTIVE:
.directive('filterCheckbox', ['$compile', function ($compile) {
return {
link:function(scope,element,attrs){
var temp = '<div class="check-box pull-left">' +
'<span class="ft" data-ng-class="{\'active\': '+attrs.ngModel+' ,\'inactive\':'+!attrs.ngModel+'}"></span>' +
'</div>' +
'<input type="checkbox" data-ng-model="'+attrs.ngModel+'" class="hide" data-ng-click="getFilteredAttrs(this)">'
element.html($compile(temp)(scope));
scope.$on('clear-filter',function(){
scope[attrs.ngModel] = false;
});
scope.$on('selected-filter',function(event,args){
//console.log('scope data',args);
//console.log('scope ', scope[attrs.ngModel]);
});
}
}
HTML:
<div class="inner-filter-section col-xs-3">
<h5 class="nova-bold">Status</h5>
<div class="outer-filter-section">
<div class="filter-option" ng-repeat=" status in filterStatusItems">
<label data-filter-checkbox class="pull-left filter-checkbox" ng-model="active" data-ng-click="setFilterObj('status')"></label>
<span class="options">{{status}}</span>
</div>
</div>
</div>
JS:
$scope.filterStatusItems = ['Success','Pending','Failed','Running','Timeout','Flow Import','Shared','Credits'];
Here is a solution in plunker
I just didn't see the use of a directive here. If you have some other behavior to add feel free to correct me.
I simply init into the scope a collection that will hold the checkboxes references :
$scope.checkboxes = [];
On the input init i add an entry in the $scope.checkboxes collection
ng-init="checkboxes.push({status:status, value:false})"
I bind this value to the input. I use the $index to bind the right object to the input :
checkboxes[$index].value
Now the uncheck mechanics :
Here i only display the status with a property value as true
On click i just set the value as false
<button ng-click="checkbox.value = false" ng-repeat="checkbox in (checkboxes | filter:{value:true}) ">
{{checkbox.status}}<span ng-if="!$last">,</span>
</button>
And that's pretty much all.
Hope it helped. If that was a mistake from me removing the directive just let me know that i can adapt a bit what i've done to your needs.
use ng-checked and set the value like true or false or assign ng-model value
<input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
Related
I have a list of Users to select for a team. Imagine that i select a User, he can either be active or inactive in his team. Now, if i don't select him at all, i should not be able to either activate or deactivate him.
This is made by a checkbox and a slider, like this:
When I click the checkbox, i need to disable the toggle. I have tried doing this by:
$("#2048").prop('disabled', true);
or
document.querySelector('[name="' + '#2048' + '"]').disabled = true;
Does not work either (And yes, i know that IDs should not be numbers, but it's because every toggle is inside a *ngFor. Still, i can use them as numbers, as jQuery can select them anyway)
Either way, i strongly believe that the only way to do something like this is to data-bind the 'disabled' attribute as some back-end variable that returns either a 'true' or 'false' value.
Something like:
<mat-slide-toggle
[id]='data.id'
class="status"
[disabled]='disableVariable'
>Active
</mat-slide-toggle>
and then:
disableVariable = someFunction(); //that returns true or false
This works, but the variable is 'too generic', i mean, every single slider will become disabled. Another problem is that this is not 'real-time', so i cant disable and enable multiple times.
Basically, it does not do the job.
What should i be doing here? If i had a way to select those tags using their unique ID's, that would fix the problem, but neither jQuery or Javascript's Query selector can disable or enable this tag.
EDIT:
A litle more of my code:
<div id="table" *ngFor="let data of User; let i = index">
<div [id]='data.id' *ngIf='data.user== 0' class="item">
<label class="container" style="width: 90%">
<input
type="checkbox"
*ngIf='data.status== 0'
id={{i}}
class="checkbox"
color=primary
checked>
<span class="checkmark"></span>
<div *ngIf='data.status== 0'>{{data.name}}
<mat-slide-toggle
[id]='data.id'
(change)=toggle(data.id)
*ngIf='data.status== 0'
color=primary
class="status"
>Active
</mat-slide-toggle>
</div>
</label>
</div>
</div>
When i add the ([ngModel)], my checkboxes stop working, and yes, i'm importing the FormsModule
You can use two-way binding to update the status of the checkbox as follows:
Add [(ngModel)] and disabled property to the input field
// Declare variable in component
CheckboxVar:boolean;
// In Html write below code
<input type="checkbox" [(ngModel)]="CheckboxVar" [disabled]="!CheckboxVar">
// Disabled checkbox when checkboxvar = false;
<input type="checkbox" [disabled]="!CheckboxVar">
Update CheckboxVar variable as per your need in your component.
Example with mat-slide-toggle
TS Code:
checked = false;
disabled = false;
HTML Code:
<input type="checkbox" [(ngModel)]="checked">
<mat-slide-toggle [disabled]="checked">
Slide me!
</mat-slide-toggle>
Now in the above example, if you checked the checkbox checked variable will be updated and if checked equals true then your toggle will be disabled.
If I understand the requirement correctly:
HTML Code:
<div *ngFor="let obj of list">
<mat-checkbox [(ngModel)]="obj.inTeam">In Team</mat-checkbox>
<br><br>
<mat-slide-toggle [(ngModel)]="obj.inTeam">Active</mat-slide-toggle>
</div>
TS Code:
list = [
{ id : 1,inTeam: false, isActive: false },
{ id : 3,inTeam: false, isActive: false },
{ id : 3,inTeam: false, isActive: false },
{ id : 4,inTeam: false, isActive: false }
]
StackBlitz
I am using AngularJS, Ionic (v 1) frameworks. On load of the mobile app screen, the checkboxes are to displayed as checked & then user may check or uncheck the checkboxes. The checkboxes are checked on load fine, however, when first time user unchecks a checkbox then the checkbox status value is undefined even though the checkbox is seen to be unchecked. After this when it is checked then it works fine whereby either the checkbox value is true or false depending upon if user checked it or unchecked it. Below if the html section of the code that is displaying the nested ng-repeat and checkboxes displayed. Also, there are multiple checkboxes that can be displayed and that is why second ng-repeat is used to load all the values for the checkboxes. Below the HTML code is the Javascript functions in controllers.
The togglegroup & isgroupshown functions are used to show or hide the checkboxes when the user clicks on the icon next to Extras.
HTML
<form name="list" class="list">
<div ng-repeat="(i, item) in menu_items track by $index">
<div class="item item-divider">
{{item.p_name}}
</div>
<select ng-show="item.Customizable == 1" ng-model="data.cmbIngredient[i]">
<option selected="selected" value="">Select the size</option>
<option ng-repeat="x in item.ProductSizes" value="{{x}}">
{{x.ProductName}}: €{{x.ProductPrice | number:2}}
</option>
</select>
<div>
{{item.p_description}}
</div>
<!-- if the Extras value equates to 1 then the checkbox is displayed-->
<div ng-show="item.Extras == 1">
<i ng-click="toggleGroup(item)" class="icon balanced icon" ng-class="isGroupShown(item) ? 'ion-minus' : 'ion-plus-round'"></i> Extras
<label ng-repeat="(j, ext) in item.ExtraDetails track by $index" class="checkbox" ng-show="isGroupShown(item)">
<input type="checkbox" ng-checked="1" ng-change="AddExtras(data.data[j].chkextras[i],item.p_id)" ng-model="data.data[j].chkextras[i]"> {{ext.CIngredientName}}
</label>
</div>
</div>
</form>
Controller functions
$scope.AddExtras=function(extraStatus,pid){
if(extraStatus == true){
//pass it to service
}
else if (extraStatus == false){
//pass it to a service
}
};
$scope.toggleGroup = function(group) {
if ($scope.isGroupShown(group)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = group;
}
};
$scope.isGroupShown = function(group) {
return $scope.shownGroup === group;
};
If you read the docs for ng-checked you can clearly read what causes the issue:
Note that this directive should not be used together with ngModel, as this can lead to unexpected behavior.
Conclusion: you should either use ng-checked or ng-model and not mix both.
You should be looking for something like this.
ng-true/false-value
This is driving me completely nuts. I can't figure out how to check/uncheck a checkbox through JavaScript.
I have the following in my HTML file:
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-9">
<div class="checkbox">
<input id="hardhat" type="checkbox" name="hardhat" checked="false" class="flat"/> Does the employee need his own hardhat?
</div>
</div>
</div>
Which translates to this in Jade:
.form-group
label.col-sm-3.control-label
.col-sm-9
.checkbox
input#hardhat(type='checkbox', name='hardhat', class='flat', checked='false')
| Does the employee need his own hardhat?
Having the checked property in HTML will ALWAYS open the window with the checkbox checked. The only way to uncheck the checkbox is to remove the checked property. What am I missing?
Because of this, nothing I do in JavaScript to check/uncheck the checkbox works :(. I was trying this:
var $modal = $('#editJob');
$modal.find('input#hardhat')['checked']=true;
Any help would be greatly appreciated!
EDIT:
function showJobInfo(event) {
document.getElementById('editJob').style.display = "block";
document.getElementById('editJob').style.visibility = "visible";
// Prevent Link from Firing
event.preventDefault();
// Retrieve job title from link rel attribute
var thisJobTitle = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = userJoblistData.map(function(arrayItem) { return arrayItem.title; }).indexOf(thisJobTitle);
// Get our Job Object
var thisJobObject = userJoblistData[arrayPosition];
// Populate the edit job popup window
var $modal = $('#editJob');
$modal.find('input#jobTitle').val(thisJobObject.title);
$modal.find('input#payRate').val(thisJobObject.payrate);
$modal.find('input#startDate').val(thisJobObject.durationstart);
$modal.find('input#endDate').val(thisJobObject.durationend);
$modal.find('input#workingHours').val(thisJobObject.workinghrs);
$modal.find('input#location').val(thisJobObject.location);
$('#hardhat').prop('checked', false);
}
I do not understand what is the problem. If you want always checked, add checked="true" html attribute.
https://jsfiddle.net/yw3obrrt/
<input id="hardhat" type="checkbox" name="hardhat" checked="true" class="flat"/>
Check in jade that checked='true'
input#hardhat(type='checkbox', name='hardhat', class='flat', checked='true')
| Does the employee need his own hardhat?
For test, not use F5 because remember your selection.
If not works.. try with jquery and use
$(document).ready(function (){
$("#hardhat").attr("checked",true);
});
https://jsfiddle.net/yw3obrrt/1/
In your example!!
$('#hardhat').prop('checked', false);
This line, unchecked checkbox!
Change to
$('#hardhat').attr('checked', true); // attr or prop
or comment this and add checked="true" in the html input!
I am trying to do inline editing on a table of data (See the plunkr)
<table class="table table-bordered">
<tr ng-repeat="data in dataset" >
<td ng-repeat="(key, value) in data" >
<div class="key-block">
<strong >{{key}}</strong>
</div>
<div class="val-block" inline-edit="data[key]" on-save="updateTodo(value)" on-cancel="cancelEdit(value)">
<input type="text" on-enter="save()" on-esc="cancel()" ng-model="model" ng-show="editMode">
<button ng-click="cancel()" ng-show="editMode">cancel</button>
<button ng-click="save()" ng-show="editMode">save</button>
<span ng-mouseenter="showEdit = true" ng-mouseleave="showEdit = false">
<span ng-hide="editMode" ng-click="edit()">{{model}}</span>
<a ng-show="showEdit" ng-click="edit()">edit</a>
</span>
</div>
</td>
</tr>
I can see in many places that we have to use a . in ng-model inside ng-repeat to avoid the scope issue. As I dont know the key already I am doing like data[key] for the model.
The input field blurs after I enter a single character.
The behavior you described is normal. If you look closely you will see that both the input value and the directive are bound to the same object i.e data[key]. When you change the value of the text input the model get updated ultimately triggering a refresh of the directive and you are back to the "list" view.
One easy solution to fix this is to use an intermediate variable between the directive and the input value and update the model only when the save button is clicked. Something like that :
//Directive
scope.newValue = null;
scope.edit = function() {
scope.editMode = true;
scope.newValue = scope.model;
$timeout(function() {
elm.find('input')[0].focus();
}, 0, false);
};
//Template
<input type="text" on-enter="save()" on-esc="cancel()" ng-model="newValue" ng-show="editMode">
You can see a modified plunker here.
I am trying to toggle the value of a checkbox using the following code:
<div class="control-group">
<label class="control-label checkbox" for="IsViewAsWebpage">
{{#if this.IsViewAsWebpage}}
<input type="hidden" id="IsViewAsWebpage" name="IsViewAsWebpage" value="true"/>
<input type="checkbox" class="enable-checkbox" checked />
{{else}}
<input type="hidden" id="IsViewAsWebpage" name="IsViewAsWebpage" value="false"/>
<input type="checkbox" class="enable-checkbox" />
{{/if}}
<span>View as Webpage</span>
</label>
</div>
'click .enable-checkbox': function (e) {
if (e.currentTarget.parentElement.htmlFor == "IsViewAsWebpage") {
this.$('#IsViewAsWebpage').is(':checked');
}
}
I know I am misssing something in the click function. I would basically want to toggle the checkbox value when the user clicks on it. Can someone point me to the right directions pls. Thank you.
When your checkbox gets clicked, it's going to toggle. That's the way checkboxes work.
If you want the hidden input to change value when the checkbox is toggled, I think what you want is this:
$(".enable-checkbox").change(function (e) {
if($(this).parent().attr("for") == "IsViewAsWebpage") {
var checked = $(this).is(":checked"); // Returns true/false.
$('#IsViewAsWebpage').attr("value", checked); // Sets true/false.
}
});
If you want to use handlebars.js to switch content when you click an check box, you will need to replace your content by calling handlebars each time you make a modification to your checkbox
$(".enable-checkbox").change(function (e) {
if($(this).parent().attr("for") == "IsViewAsWebpage") {
var checked = $(this).is(":checked");
IsViewAsWebpage = checked;
$("#yourcontainer").html(Handlebars.compile(yourtemplatesource));
}
}
then your IsViewAsWebpage variable should be global and your mustache condition should only be :
{{#if IsViewAsWebpage}}
But this is complicated for nothing... just use Aesthete solution, it will save you a lot of time.