Angularjs set checked radio not working - angularjs

I have 3 radio buttons:
<label ng-repeat="mode in opMode.groupMode" class="radio-inline" title="{{mode.title}}">
<input id="rd{{mode.id}}" type="radio" class="panel-load-radio" ng-model="opdtMode.groupMode"
name="inlineRadioOptions" value="{{mode.id}}"
ng-change="changeOpdtMode(mode.id, '{{opdtMode.groupMode}}')">
{{mode.name}}
</label>
Here is Angularjs code:
$scope.opMode = { groupMode: [
{ name: "ModuleType", title: "Load processes by Module type", id: "ModuleType", isDefault: false },
{ name: "OpGroup", title: "Load processes by Operation group", id: "OpGroup", isDefault: true },
{ name: "MachineType", title: "Load processes by Machine type", id: "MachineType", isDefault: false }
]};
If isChange = true, show confirm mbox. If User click cancel, set oldValue and checked previous radio. I wrote this. However it's not working as expected:
$scope.changeOpdtMode = function (newValue, oldValue) {
if(isChange){
const msg = getMsgById(29, msgLostData);
const r = confirm(msg.value);
if (r === true) {
const lang = $scope.layoutLang.selectedLang;
loadLayout(null, lang, newValue);
window.isChange = false;
} else {
$scope.opdtMode.groupMode = oldValue;
}
}else{
const lang = $scope.layoutLang.selectedLang;
loadLayout(null, lang, newValue);
}
}

After 2 hours researched:
I post my answer here for everyone may see as the same issue.
<label ng-repeat="mode in opMode" class="radio-inline" title="{{mode.title}}">
<input type="radio" class="panel-load-radio" ng-value="mode.id"
ng-model="$parent.opdtMode" ng-change="changeOpdtMode(mode.id, '{{opdtMode}}')">
{{mode.name}}
</label>
Need to remove name="inlineRadioOptions" and add $parent into the model.
$scope.opdtMode = "OpGroup";
$scope.opMode = [{ name: "ModuleType", title: "Load processes by Module type", id: "ModuleType" },
{ name: "OpGroup", title: "Load processes by Operation group", id: "OpGroup" },
{ name: "MachineType", title: "Load processes by Machine type", id: "MachineType" }];
$scope.changeOpdtMode = function (newValue, oldValue) {
if(isChange){
const msg = getMsgById(29, msgLostData);
const r = confirm(msg.value);
if (r === true) {
const lang = $scope.layoutLang.selectedLang;
loadLayout(null, lang, newValue);
window.isChange = false;
} else {
$scope.opdtMode = oldValue;
}
}else{
const lang = $scope.layoutLang.selectedLang;
loadLayout(null, lang, newValue);
}
}

Related

When checkbox is uncheck, I want to return all my list

when I uncheck my text box, its not returning an selectedItemsList
.Hope you understand my problem.
changeSelection() {
this.checkedIDs = []
this.selectedItemsList = this.DisplayProductList.filter((value, index) => {
if (value.isChecked == true) {
return value.isChecked
}
else{
this.selectedItemsList = this.ProductData;
}
});
this.router.navigate(['pipeline/cluster/policies'])
this.sendclusteridApi()
}
if (value.isChecked == false){
this.selectedItemsList = this.ProductData;
}
else{
this.selectedItemsList = this.ProductData;
}
You are definitely wrong here. Doing the same thing in if and else conditions.
Make changes to this code as you need, follow same structure:
HTML:
<mat-checkbox (click)="showData()" (checked)="(isChecked)" (change)="isChecked = !isChecked"></mat-checkbox>
<!-- below part only to visually see the change -->
<div *ngFor="let elem of displayedItems">
<p>{{ elem.name }}</p>
</div>
Typescript:
displayedItems = [];
selectedItemsList = [
{
item1: 'hello',
name: 'item1',
},
{
item2: 'hello',
name: 'item3',
},
{
item3: 'hello',
name: 'item3',
},
];
showData() {
if (this.isChecked === false) {
this.displayedItems = this.selectedItemsList;
} else {
this.displayedItems = [];
}
}

How to select a value for option dropdown in angularJS UnitTest

My html code is something like this and I want to select a value from dropdown and verify the same in AngularJS UnitTestCase using Jasmine
I tried using option.value but it's not working out..
<select id="company" ng-model="company" ng-change="companychange(company)" ng-options="company.ID as company.Name for company in companies"></select>
My AngularJS UnitTestCase is something like this
//somecode has been left out
$templateCache.put('selectcompany.html', directiveTemplate);
templateHtml = $templateCache.get('selectcompany.html');
formElem = angular.element('<div>' + templateHtml + '</div>');
//console.log(directiveTemplate);
$compile(formElem)($scope);
form = $scope.companyform;
companyform = form;
form2 = $compile(directiveTemplate)($scope);
$scope.$apply('companies=[{ Name: "Gold", value:0, ID: 0 },{ Name: "Silver", value:1, ID: 1 }, { Name: "Bronze", value: 2, ID: 2 }]');
}));
describe(' company ', function () {
it('selecting a dropdown ', function () {
var options = form2.find('[id="company"]')[0];
angular.element(options["value='2'"]).trigger('click');
$scope.$digest();
console.log(options.innerHTML);
expect($scope.company).toBe(2);
});
});

Vue.js filtering on array

I am trying to filter an array using a computed property in vue.js. I would like to search on on multiple fields, name, state, tags etc.
My data:
events: [
{
id: 1,
name: 'Name of event',
url: '#',
datetime: '2017-05-10T00:00:00Z',
description: 'The full text of the event',
state: 'VIC',
tags: [
'ordinary',
'advanced'
]
},
{
id: 2,
name: 'Another event',
url: '#',
datetime: '2017-05-12T00:00:00Z',
description: 'The full text of the event',
state: 'VIC',
tags: [
'beginner'
]
},
{
id: 3,
name: 'Great event',
url: '#',
datetime: '2017-05-18T00:00:00Z',
description: 'The full text of the event',
state: 'NSW',
tags: [
'beginner'
]
}
]
},
The following function works as expected, however I cant work out how to have it search the items in 'tags' (commented out).
searchevents: function(){
let result = this.events
if (this.filterValue){
result = result.filter(event =>
event.name.toLowerCase().includes(this.filterValue.toLowerCase()) ||
event.state.toLowerCase().includes(this.filterValue.toLowerCase())
// event.tags.toLowerCase().values().includes(this.filterValue.toLowerCase())
)
}
return result
}
The following returns a blank array, this method works ok when i have done it in angular but not in vue.
searchevents2: function(){
var searchRegex = new RegExp(this.filterValue,'i')
this.events.filter(function(event){
return !self.filterValue || searchRegex.test(event.name) || searchRegex.test(event.state)
})
}
Ideally I would either like to be able to list array items to filter by or just filter by the entire array.
Appreciate any help, first post here so be gentle. I have a lot more experience with Python than Javascript so i may also use incorrect terminology at times.
You weren't too far off.
For your searchEvents filter, you just needed to add the tag filter. Here's how you might do that.
searchevents: function(){
let result = this.events
if (!this.filterValue)
return result
const filterValue = this.filterValue.toLowerCase()
const filter = event =>
event.name.toLowerCase().includes(filterValue) ||
event.state.toLowerCase().includes(filterValue) ||
event.tags.some(tag => tag.toLowerCase().includes(filterValue))
return result.filter(filter)
}
Array.some() is a standard array method that returns true if any element of the array passes your test.
searchevents2: function(){
const searchRegex = new RegExp(this.filterValue,'i')
return this.events.filter(event =>
!this.filterValue || searchRegex.test(event.name) || searchRegex.test(event.state))
}
With searchEvents2 you really only left an errant self in there. Either you needed to set self before you executed the filter, or, as I have done here, turned it into an arrow function.
Example.
const app = new Vue ({
el: '#app',
data: {
search: '',
userList: [
{
id: 1,
name: "Prem"
},
{
id: 1,
name: "Chandu"
},
{
id: 1,
name: "Shravya"
}
]
},
computed: {
filteredAndSorted(){
// function to compare names
function compare(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
return this.userList.filter(user => {
return user.name.toLowerCase().includes(this.search.toLowerCase())
}).sort(compare)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<div class="search-wrapper">
<input type="text" v-model="search" placeholder="Search title.."/>
<label>Search Users:</label>
</div>
<ul>
<li v-for="user in filteredAndSorted">{{user.name}}</li>
</ul>
</div>

show checkbox elements of an array of checkboxes

I have got a set of radiobuttons and an array of checkboxes. When i click radiobutton1 it should load first checkbox element from the array and when i click radiobutton2 it should load remaining 3 checkbox elements from the array.But it shows all 4 checkboxes in both the cases. I tried like this.
In HTML
<form>
<label class="radio-inline" >
<input value="1" type="radio" ng-model="radioption" >RB1</label>
<label class="radio-inline">
<input value="2" type="radio" ng-model="radioption" >RB2</label>
<div class="">
<label ng-repeat="channel in channels | filter:myFilter" >
<input type="checkbox" name="selectedChannels[]" value="{{channel.value}}"
ng-model="channel.selected" >{{channel.name}}
</label></div>
</form>
In Controller
App.controller('ReportController', ['$scope', 'Report', function($scope, Report){
var self = this;
$scope.channels = [{ name: 'A', selected: false, value: '1',visible:false },
{ name: 'B', selected: false, value: '2' ,visible:false},
{ name: 'C', selected: false, value: '3' ,visible:false},
{ name: 'D', selected: false, value: '4' ,visible:false}
];
$scope.selection = [];
$scope.selectedChannels = function selectedChannels() {
return Report($scope.channels, { selected: true } );
};
$scope.$watch('channels|filter:{selected:true}', function (new) {
$scope.selection = new.map(function (channel) {
return channel.value;
});
}, true);
$scope.myFilter = function(){
if ($scope.radioption == '1'){
return $scope.channels[0].visible = true;
}
else if ($scope.radioption == '2'){
return [$scope.channels[1],{ visible: true },
$scope.channels[2],{ visible: true },
$scope.channels[3],{ visible: true }];
}
});
}]);
I think you should approach this problem differently but if you want to use a filter try this
$scope.myFilter = function (channel) {
if ($scope.radioption == 1) {
if (channel.name == 'A') {
return true;
}
else {
return false;
}
}
else if ($scope.radioption == 2) {
if (channel.name == 'A') {
return false;
}
else {
return true;
}
}
else {
return false;
}
}
or you can add radioption column to channels array
$scope.channels = [{ name: 'A', selected: false, value: '1', radioption: 1 },
{ name: 'B', selected: false, value: '2', radioption: 2 },
{ name: 'C', selected: false, value: '3', radioption: 2 },
{ name: 'D', selected: false, value: '4', radioption: 2 }
];
and use ng-show
<input type="checkbox" ng-show="channel.radioption == radioption" name="selectedChannels[]" value="{{channel.value}}"
ng-model="channel.selected">{{channel.name}}
You need to register your filter with angularJS. e.g.
app.filter('myFilter', function() {
return function(input) {
var output;
// Do filter work here
return output;
}
Then you can use your filter in the HTML.
Also - filter should get input and return a filtered output. I think it make less sense to return a strict output regardless of the input given to it.
Take a look here, for example:
https://scotch.io/tutorials/building-custom-angularjs-filters

ngTable select all filtered data

I'm trying to select only the rows from an ng-table with filtered data. Using the following code filters the table rows but even the rows that aren't shown are being selected:
controller:
let sampleData = [{id: 1, name: 'John Doe', gender: 'Male'},
{id: 2, name: 'Jane Doe', gender: 'Female'},
{id: 3, name: 'Mary Jane', gender: 'Female'},
{id: 4, name: 'Mary Poppins', gender: 'Female'}];
$scope.tableParams = new NgTableParams({
}, {
dataset: sampleData
});
$scope.checkboxes = {
checked: false,
items: {}
};
$scope.$watch(() => {
return $scope.checkboxes.checked;
}, (value) => {
sampleData.map((item) => {
$scope.checkboxes.items.id = value;
});
});
$scope.$watch(() => {
return $scope.checkboxes.items;
}, () => {
let checked = 0;
let unchecked = 0;
let total = sampleData.length;
sampleData.map((item) => {
if ($scope.checkboxes.items.id) {
checked++;
} else {
unchecked++;
}
});
if (unchecked === 0 || checked === 0) {
$scope.checkboxes.checked = checked === total;
}
angular.element($element[0].getElementsByClassName('select-all')).prop('indeterminate', (checked != 0 && unchecked != 0));
});
html:
<script type="text/ng-template" id="checkbox.html">
<input type="checkbox" ng-model="checkboxes.checked" class="select-all" value="">
</script>
<table class="table" ng-table="tableParams" show-filter="true">
<tr ng-repeat="item in $data track by $index">
<td header="'checkbox.html'">
<input type="checkbox" ng-model="checkboxes.items[item.id]">
</td>
<td data-title="'Name'" filter="{'name': 'text'}">
{{item.name}}
</td>
<td data-title="'Gender'" filter="{'gender': 'text'}">
{{item.gender}}
</td>
</tr>
</table>
When the table is filtered via name or gender, the table rerenders with the filtered data. When you click on the select all checkbox while the table is filtered, the filtered rows are selected. Unfortunately, when you clear the filter, the previously filtered out rows are also selected. The same is true when selecting all the filtered rows and then triggering an action that's supposed to get the selected items. (All ids are selected for the action.)
How can I only select the filtered rows? Thank you.
Okay, I got it to work. I just added a tableData object to the $scope so I can store the filtered data there. That's what I used for checking the selected items.
let sampleData = [{id: 1, name: 'John Doe', gender: 'Male'},
{id: 2, name: 'Jane Doe', gender: 'Female'},
{id: 3, name: 'Mary Jane', gender: 'Female'},
{id: 4, name: 'Mary Poppins', gender: 'Female'}];
$scope.tableData = {
filteredData: [],
checkboxes: {
checked: false,
items: {}
}
};
$scope.tableParams = new NgTableParams({
page: 1,
count: 10
}, {
total: data.length;
getData: ($defer, params) => {
let filter = params.filter();
let count = params.count();
let page = params.page();
let filteredData = filter ? $filter('filter')(data, filter) : data;
params.total(filteredData.length);
$scope.tableData.filteredData = filteredData;
$defer.resolve(filteredData.slice((page - 1) * count, page * count));
}
});
$scope.$watch(() => {
return $scope.tableData.checkboxes.checked;
}, (value) => {
$scope.tableData.filteredData.map((item) => {
$scope.tableData.checkboxes.items[item].id = value;
});
});
$scope.$watch(() => {
return $scope.tableData.checkboxes.items;
}, () => {
let checked = 0;
let unchecked = 0;
let data = $scope.tableData.filteredData;
let total = data.length;
let checkboxes = $scope.tableData.checkboxes;
data.map((item) => {
if (checkboxes.items[item].id) {
checked++;
} else {
unchecked++;
}
});
if (unchecked === 0 || checked === 0) {
checkboxes.checked = checked === total;
}
angular.element($element[0].getElementsByClassName('select-all')).prop('indeterminate', (checked != 0 && unchecked != 0));
});
Not really sure if this is the best way to go about it. Also, this doesn't change the select all checkbox's state to indeterminate when you filter > select all > clear filter.
in your second watch, change to return $scope.tableData.filteredData; may solve your problem

Resources