AngularJS Dropdown Multiselect adding custom button - angularjs
I am currently stuck in a situation where I have to add a button to drop down options but can't find any help to add custom button to drop down options using this library
main.js
$scope.example14model = [];
$scope.example14settings = {
scrollableHeight: '200px',
scrollable: true,
enableSearch: true
};
$scope.example14data = [{
"label": "Alabama",
"id": "AL"
}, {
"label": "Alaska",
"id": "AK"
}
];
main.html
<div ng-dropdown-multiselect=""
options="example14data"
selected-model="example14model"
checkboxes="true"
extra-settings="example14settings"></div>
How can I add button to my drop down options? Any help will be highly appreciated.
I think this is what you are looking for :
https://jsfiddle.net/michaeldeongreen/22et6sao/9/
JS
'use strict';
var app = angular.module('myApp', ['angularjs-dropdown-multiselect']);
app.controller('AppCtrl', function ($scope) {
$scope.example14model = [];
$scope.example14settings = {
scrollableHeight: '200px',
scrollable: true,
enableSearch: true
};
$scope.example14data = [{
"label": "Alabama",
"id": "AL"
}, {
"label": "Alaska",
"id": "AK"
}, {
"label": "American Samoa",
"id": "AS"
}, {
"label": "Arizona",
"id": "AZ"
}, {
"label": "Arkansas",
"id": "AR"
}, {
"label": "California",
"id": "CA"
}, {
"label": "Colorado",
"id": "CO"
}, {
"label": "Connecticut",
"id": "CT"
}, {
"label": "Delaware",
"id": "DE"
}, {
"label": "District Of Columbia",
"id": "DC"
}, {
"label": "Federated States Of Micronesia",
"id": "FM"
}, {
"label": "Florida",
"id": "FL"
}, {
"label": "Georgia",
"id": "GA"
}, {
"label": "Guam",
"id": "GU"
}, {
"label": "Hawaii",
"id": "HI"
}, {
"label": "Idaho",
"id": "ID"
}, {
"label": "Illinois",
"id": "IL"
}, {
"label": "Indiana",
"id": "IN"
}, {
"label": "Iowa",
"id": "IA"
}, {
"label": "Kansas",
"id": "KS"
}, {
"label": "Kentucky",
"id": "KY"
}, {
"label": "Louisiana",
"id": "LA"
}, {
"label": "Maine",
"id": "ME"
}, {
"label": "Marshall Islands",
"id": "MH"
}, {
"label": "Maryland",
"id": "MD"
}, {
"label": "Massachusetts",
"id": "MA"
}, {
"label": "Michigan",
"id": "MI"
}, {
"label": "Minnesota",
"id": "MN"
}, {
"label": "Mississippi",
"id": "MS"
}, {
"label": "Missouri",
"id": "MO"
}, {
"label": "Montana",
"id": "MT"
}, {
"label": "Nebraska",
"id": "NE"
}, {
"label": "Nevada",
"id": "NV"
}, {
"label": "New Hampshire",
"id": "NH"
}, {
"label": "New Jersey",
"id": "NJ"
}, {
"label": "New Mexico",
"id": "NM"
}, {
"label": "New York",
"id": "NY"
}, {
"label": "North Carolina",
"id": "NC"
}, {
"label": "North Dakota",
"id": "ND"
}, {
"label": "Northern Mariana Islands",
"id": "MP"
}, {
"label": "Ohio",
"id": "OH"
}, {
"label": "Oklahoma",
"id": "OK"
}, {
"label": "Oregon",
"id": "OR"
}, {
"label": "Palau",
"id": "PW"
}, {
"label": "Pennsylvania",
"id": "PA"
}, {
"label": "Puerto Rico",
"id": "PR"
}, {
"label": "Rhode Island",
"id": "RI"
}, {
"label": "South Carolina",
"id": "SC"
}, {
"label": "South Dakota",
"id": "SD"
}, {
"label": "Tennessee",
"id": "TN"
}, {
"label": "Texas",
"id": "TX"
}, {
"label": "Utah",
"id": "UT"
}, {
"label": "Vermont",
"id": "VT"
}, {
"label": "Virgin Islands",
"id": "VI"
}, {
"label": "Virginia",
"id": "VA"
}, {
"label": "Washington",
"id": "WA"
}, {
"label": "West Virginia",
"id": "WV"
}, {
"label": "Wisconsin",
"id": "WI"
}, {
"label": "Wyoming",
"id": "WY"
}];
$scope.example2settings = {
displayProp: 'id'
};
});
var directiveModule = angular.module('angularjs-dropdown-multiselect', []);
directiveModule.directive('ngDropdownMultiselect', ['$filter', '$document', '$compile', '$parse',
function ($filter, $document, $compile, $parse) {
return {
restrict: 'AE',
scope: {
selectedModel: '=',
options: '=',
extraSettings: '=',
events: '=',
searchFilter: '=?',
translationTexts: '=',
groupBy: '#'
},
template: function (element, attrs) {
var checkboxes = attrs.checkboxes ? true : false;
var groups = attrs.groupBy ? true : false;
var template = '<div class="multiselect-parent btn-group dropdown-multiselect">';
template += '<button type="button" class="dropdown-toggle" ng-class="settings.buttonClasses" ng-click="toggleDropdown()">{{getButtonText()}} <span class="caret"></span></button>';
template += '<ul class="dropdown-menu dropdown-menu-form" ng-style="{display: open ? \'block\' : \'none\', height : settings.scrollable ? settings.scrollableHeight : \'auto\' }" style="overflow: scroll" >';
template += '<li ng-hide="!settings.showCheckAll || settings.selectionLimit > 0"><a data-ng-click="selectAll()"><span class="glyphicon glyphicon-ok"></span> {{texts.checkAll}}</a>';
template += '<li ng-show="settings.showUncheckAll"><a data-ng-click="deselectAll();"><span class="glyphicon glyphicon-remove"></span> {{texts.uncheckAll}}</a></li>';
template += '<li ng-hide="(!settings.showCheckAll || settings.selectionLimit > 0) && !settings.showUncheckAll" class="divider"></li>';
template += '<li ng-show="settings.enableSearch"><div class="dropdown-header"><input type="text" class="form-control" style="width: 100%;" ng-model="searchFilter" placeholder="{{texts.searchPlaceholder}}" /></li>';
template += '<li ng-show="settings.enableSearch" class="divider"></li>';
if (groups) {
template += '<li ng-repeat-start="option in orderedItems | filter: searchFilter" ng-show="getPropertyForObject(option, settings.groupBy) !== getPropertyForObject(orderedItems[$index - 1], settings.groupBy)" role="presentation" class="dropdown-header">{{ getGroupTitle(getPropertyForObject(option, settings.groupBy)) }}</li>';
template += '<li ng-repeat-end role="presentation">';
} else {
template += '<li role="presentation" ng-repeat="option in options | filter: searchFilter">';
}
template += '<a role="menuitem" tabindex="-1" ng-click="setSelectedItem(getPropertyForObject(option,settings.idProp))">';
if (checkboxes) {
template += '<div class="checkbox"><label><input class="checkboxInput" type="checkbox" ng-click="checkboxClick($event, getPropertyForObject(option,settings.idProp))" ng-checked="isChecked(getPropertyForObject(option,settings.idProp))" /> {{getPropertyForObject(option, settings.displayProp)}}</label></div></a>';
} else {
template += '<span data-ng-class="{\'glyphicon glyphicon-ok\': isChecked(getPropertyForObject(option,settings.idProp))}"></span> {{getPropertyForObject(option, settings.displayProp)}}</a>';
}
template += '</li>';
template += '<li class="divider" ng-show="settings.selectionLimit > 1"></li>';
template += '<li role="presentation" ng-show="settings.selectionLimit > 1"><a role="menuitem">{{selectedModel.length}} {{texts.selectionOf}} {{settings.selectionLimit}} {{texts.selectionCount}}</a></li>';
template += '</ul>';
template += '</div>';
element.html(template);
},
link: function ($scope, $element, $attrs) {
var $dropdownTrigger = $element.children()[0];
$scope.toggleDropdown = function () {
$scope.open = !$scope.open;
};
$scope.checkboxClick = function ($event, id) {
$scope.setSelectedItem(id);
$event.stopImmediatePropagation();
};
$scope.externalEvents = {
onItemSelect: angular.noop,
onItemDeselect: angular.noop,
onSelectAll: angular.noop,
onDeselectAll: angular.noop,
onInitDone: angular.noop,
onMaxSelectionReached: angular.noop
};
$scope.settings = {
dynamicTitle: true,
scrollable: false,
scrollableHeight: '300px',
closeOnBlur: true,
displayProp: 'label',
idProp: 'id',
externalIdProp: 'id',
enableSearch: false,
selectionLimit: 0,
showCheckAll: true,
showUncheckAll: true,
closeOnSelect: false,
buttonClasses: 'btn btn-default',
closeOnDeselect: false,
groupBy: $attrs.groupBy || undefined,
groupByTextProvider: null,
smartButtonMaxItems: 0,
smartButtonTextConverter: angular.noop
};
$scope.texts = {
checkAll: 'Check All',
uncheckAll: 'Uncheck All',
selectionCount: 'checked',
selectionOf: '/',
searchPlaceholder: 'Search...',
buttonDefaultText: 'Select',
dynamicButtonTextSuffix: 'checked'
};
$scope.searchFilter = $scope.searchFilter || '';
if (angular.isDefined($scope.settings.groupBy)) {
$scope.$watch('options', function (newValue) {
if (angular.isDefined(newValue)) {
$scope.orderedItems = $filter('orderBy')(newValue, $scope.settings.groupBy);
}
});
}
angular.extend($scope.settings, $scope.extraSettings || []);
angular.extend($scope.externalEvents, $scope.events || []);
angular.extend($scope.texts, $scope.translationTexts);
$scope.singleSelection = $scope.settings.selectionLimit === 1;
function getFindObj(id) {
var findObj = {};
if ($scope.settings.externalIdProp === '') {
findObj[$scope.settings.idProp] = id;
} else {
findObj[$scope.settings.externalIdProp] = id;
}
return findObj;
}
function clearObject(object) {
for (var prop in object) {
delete object[prop];
}
}
if ($scope.singleSelection) {
if (angular.isArray($scope.selectedModel) && $scope.selectedModel.length === 0) {
clearObject($scope.selectedModel);
}
}
if ($scope.settings.closeOnBlur) {
$document.on('click', function (e) {
var target = e.target.parentElement;
var parentFound = false;
while (angular.isDefined(target) && target !== null && !parentFound) {
if (_.contains(target.className.split(' '), 'multiselect-parent') && !parentFound) {
if (target === $dropdownTrigger) {
parentFound = true;
}
}
target = target.parentElement;
}
if (!parentFound) {
$scope.$apply(function () {
$scope.open = false;
});
}
});
}
$scope.getGroupTitle = function (groupValue) {
if ($scope.settings.groupByTextProvider !== null) {
return $scope.settings.groupByTextProvider(groupValue);
}
return groupValue;
};
$scope.getButtonText = function () {
if ($scope.settings.dynamicTitle && ($scope.selectedModel.length > 0 || (angular.isObject($scope.selectedModel) && _.keys($scope.selectedModel).length > 0))) {
if ($scope.settings.smartButtonMaxItems > 0) {
var itemsText = [];
angular.forEach($scope.options, function (optionItem) {
if ($scope.isChecked($scope.getPropertyForObject(optionItem, $scope.settings.idProp))) {
var displayText = $scope.getPropertyForObject(optionItem, $scope.settings.displayProp);
var converterResponse = $scope.settings.smartButtonTextConverter(displayText, optionItem);
itemsText.push(converterResponse ? converterResponse : displayText);
}
});
if ($scope.selectedModel.length > $scope.settings.smartButtonMaxItems) {
itemsText = itemsText.slice(0, $scope.settings.smartButtonMaxItems);
itemsText.push('...');
}
return itemsText.join(', ');
} else {
var totalSelected;
if ($scope.singleSelection) {
totalSelected = ($scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp])) ? 1 : 0;
} else {
totalSelected = angular.isDefined($scope.selectedModel) ? $scope.selectedModel.length : 0;
}
if (totalSelected === 0) {
return $scope.texts.buttonDefaultText;
} else {
return totalSelected + ' ' + $scope.texts.dynamicButtonTextSuffix;
}
}
} else {
return $scope.texts.buttonDefaultText;
}
};
$scope.getPropertyForObject = function (object, property) {
if (angular.isDefined(object) && object.hasOwnProperty(property)) {
return object[property];
}
return '';
};
$scope.selectAll = function () {
$scope.deselectAll(false);
$scope.externalEvents.onSelectAll();
angular.forEach($scope.options, function (value) {
$scope.setSelectedItem(value[$scope.settings.idProp], true);
});
};
$scope.deselectAll = function (sendEvent) {
sendEvent = sendEvent || true;
if (sendEvent) {
$scope.externalEvents.onDeselectAll();
}
if ($scope.singleSelection) {
clearObject($scope.selectedModel);
} else {
$scope.selectedModel.splice(0, $scope.selectedModel.length);
}
};
$scope.setSelectedItem = function (id, dontRemove) {
var findObj = getFindObj(id);
var finalObj = null;
if ($scope.settings.externalIdProp === '') {
finalObj = _.find($scope.options, findObj);
} else {
finalObj = findObj;
}
if ($scope.singleSelection) {
clearObject($scope.selectedModel);
angular.extend($scope.selectedModel, finalObj);
$scope.externalEvents.onItemSelect(finalObj);
if ($scope.settings.closeOnSelect) $scope.open = false;
return;
}
dontRemove = dontRemove || false;
var exists = _.findIndex($scope.selectedModel, findObj) !== -1;
if (!dontRemove && exists) {
$scope.selectedModel.splice(_.findIndex($scope.selectedModel, findObj), 1);
$scope.externalEvents.onItemDeselect(findObj);
} else if (!exists && ($scope.settings.selectionLimit === 0 || $scope.selectedModel.length < $scope.settings.selectionLimit)) {
$scope.selectedModel.push(finalObj);
$scope.externalEvents.onItemSelect(finalObj);
}
if ($scope.settings.closeOnSelect) $scope.open = false;
};
$scope.isChecked = function (id) {
if ($scope.singleSelection) {
return $scope.selectedModel !== null && angular.isDefined($scope.selectedModel[$scope.settings.idProp]) && $scope.selectedModel[$scope.settings.idProp] === getFindObj(id)[$scope.settings.idProp];
}
return _.findIndex($scope.selectedModel, getFindObj(id)) !== -1;
};
$scope.externalEvents.onInitDone();
}
};
}]);
HMTL
<div ng-app="myApp" ng-controller="AppCtrl">
<div ng-dropdown-multiselect="" options="example14data" selected-model="example14model" checkboxes="true" extra-settings="example14settings"></div> <pre>Selected Model: {{example14model}} | json</pre>
Related
Generating forms dynamically using json schema with angularjs
I have a json schema which is something like below: var schema = { "type": "object", "properties": { "requestedFor": { "type": "string" }, "location": { "type": "string" }, "shortDescription":{ "type": "string" }, "description": { "type": "string" } } }; var options = { "fields": { "requestedFor": { "requestedFor": "text", "label": "*Name" }, "location": { "type": "text", "label": "*Location" }, "shortDescription":{ "type": "text", "label": "Short Description" }, "description": { "type": "textarea", "label": "Description", "rows": 5, "cols": 60, "label": "", "wordlimit": 250 } }, "form": { "attributes": { "method": "POST", "action": "#", "enctype": "multipart/form-data" }, "buttons": { "submit": { "value": "Submit" } } } }; So i want to use this json schema to create a custom directive on the fly using angularjs. So for that i have created the code something like below: var app = angular.module("app", []) .directive("wrapper", function($compile, $interval) { return { scope: { directiveName: "=" }, link: function(scope, elem, attrs) { scope.$watch("directiveName", function() { var html = "<" + scope.directiveName + "></" + scope.directiveName + ">"; elem.html(html); $compile(elem.contents())(scope); }); } } }).controller("addDirectives", function($scope, $interval) { let directiveNames = ['d1', 'd2', 'd3', "d4"]; $scope.directiveName = directiveNames[0]; }).directive("d1", function() { return { template: "<input type='text'>Requested For</input>" } }).directive("d2", function() { return { template: "<input type='text'>Location</input>" } }).directive("d3", function() { return { template: "<input type='text'>Short Description</input>" } }).directive("d4", function(){ return { template: "<input type='textarea'>Description</input>" } }) Here my intention is to use this json schema to generate the form dynamically because i have so many json files available so for that i need to create different custom directives. <!DOCTYPE html> <html ng-app="app"> <head> <body ng-controller="addDirectives"> <div class="container"> <div class="row"> <div class="col-md-12"> <div id="form"></div> </div> </div> </div> </body> </html> So can anybody provide any solution for this?
AngularUI-Bootstrap Typeahead: Grouping titles by type
I am implementing typeahead using AngularUI-Bootstrap. I need to show the results grouped based on some values coming from the database. Here's a example of result [{ "id": 1, "label": "type_1", "titles": [{ "id": 1, "label": "title_1" }, { "id": 2, "label": "title_2" }, { "id": 3, "label": "title_3" }] }, { "id": 2, "label": "type_2", "titles": [{ "id": 4, "label": "title_4" }, { "id": 6, "label": "title_6" }] }, { "id": 3, "label": "type_3", "titles": [{ "id": 8, "label": "title_8" }, { "id": 9, "label": "title_9" }] }] How can grouping titles by type in AngularUI-Bootstrap Typeahead
JB Nizet is right, you should use a custom template (default). Look at // view <script type="text/ng-template" id="typeahead-match.html"> <div ng-if="match.model.isGroup">{{match.label}}</div> <a ng-if="!match.model.isGroup" ng-bind-html="match.label | uibTypeaheadHighlight:query"> {{match.label}} </a> </script> <input type="text" ng-model="selected" uib-typeahead="item as item.label for item in getItems($viewValue)" class="form-control" typeahead-template-url="typeahead-match.html"> // controller myApp.controller('MainController', ['$scope', function($scope) { var data = [{ "id": 1, "label": "type_1", "titles": [{ "id": 1, "label": "title_1" }, { "id": 2, "label": "title_2" }, { "id": 3, "label": "title_3" }] }, { "id": 2, "label": "type_2", "titles": [{ "id": 4, "label": "title_4" }, { "id": 6, "label": "title_6" }] }, { "id": 3, "label": "type_3", "titles": [{ "id": 8, "label": "title_8" }, { "id": 9, "label": "title_9" }] }]; $scope.getItems = function(text) { var result = []; _.each(data, function(group) { result.push({ label: group.label, isGroup: true }); _.each(group.titles, function(item) { if(_.startsWith(item.label, text)) { result.push(item); } }); if(result && result[result.length-1].isGroup) { result.pop(); } }); return result; }; }]); Example
Moving JSon Response into Dropdown
I have a Json Response as given below JSON : { "json": { "response": { "servicetype": "1", "functiontype": "10011", "statuscode": "0", "statusmessage": "Success", "data": { "assignedroles": [ { "roleid": 162, "rolename": "Admin", "roleinformation": { "A": [ { "1st floor": 10 } ] } }, { "roleid": 163, "rolename": "Resident", "roleinformation": { "A": [ { "1st floor": 10 } ] } } ], "unassignedroles": [ { "roleid": 36, "rolename": "Product Managers", "divisionlabel": "Department ", "subdivisionlabel": "Category", "roleinformation": { "QA": [ { "White Box Testing": 0 } ] } }, { "roleid": 108, "rolename": "Teacher", "divisionlabel": "Class", "subdivisionlabel": "Div", "roleinformation": "" }, { "roleid": 115, "rolename": "Staff", "divisionlabel": "Class", "subdivisionlabel": "Section", "roleinformation": { "1": [ { "A": 0 } ] } }, { "roleid": 116, "rolename": "Student", "divisionlabel": "Class", "subdivisionlabel": "Section", "roleinformation": { "1": [ { "A": 0 } ] } }, { "roleid": 184, "rolename": "CANt_MANAGE_Gbase", "divisionlabel": "Division", "subdivisionlabel": "SubDivision", "roleinformation": { "Div": [ { "Sdiv": 0 }, { "Sdiv1": 0 } ] } }, { "roleid": 191, "rolename": "Legend", "divisionlabel": "a", "subdivisionlabel": "b" } ] } } } } need to get rolename of both assigned and unassigned values from json response. I am able to get in two arrays, but couldn't work with moving both. HTML: <div class="form-group"> <label class="control-label col-sm-10" for="groupz">Select Role*</label> <select class="form-control" name="role" ng-model="model.rolename" ng-change="GetAssignRole(model.rolename)"> <option selected>Select Roles</option> <option ng-repeat="item in model.roles track by $index" value="{{item}}">{{item}}</option> </select> <div> JS: UserService.getAssignRoles(json).then(function(response) { if (response.json.response.statuscode == 0 && response.json.response.statusmessage == 'Success') { $scope.model.assignroles = []; var resdata =response.json.response.data; var unasresdata = response.json.response.data.unassignedroles; var assresdata = response.json.response.data.assignedtoles; $scope.model.assignroles.push(unasresdata); $scope.model.assignroles.push(assresdata); } }); }; I couldn't figure out how to move both the datas into dropdown. If something is empty in assigned or unassigned , it gives undefined in response.But I am able to get two arrays inside assignRoles .
Concat unassignedroles[] and assignedroles[] to make single array.Just try below code.It might help u. UserService.getAssignRoles(json).then(function(response) { if (response.json.response.statuscode == 0 && response.json.response.statusmessage == 'Success') { $scope.model.assignroles = [],assignrolesArray = []; var unasresdata = response.json.response.data.unassignedroles; var assresdata = response.json.response.data.assignedtoles; assignrolesArray = unasresdata.concat(assresdata); $scope.model.assignroles = assignrolesArray; } }); HTML <div class="form-group"> <label class="control-label col-sm-10" for="groupz">Select Role*</label> <select class="form-control" name="role" ng-model="model.rolename" ng-change="GetAssignRole(model.rolename)"> <option selected>Select Roles</option> <option ng-repeat="role in model.assignroles track by $index" value="{{role.rolename}}">{{role.rolename}}</option> </select> <div>
How do I filter a parent/child list in angular 2
In angular 1, I have a tree list that I can filter at any level by searching a textbox. Here is a fiddle with a working demo. I am trying to convert this to angular 2 with the results as shown in the provided picture. I am stuck on converting this line of code to angular 2: lvl_2.children = $filter('filter')(lvl_2.children, newVal); Here is a Plunker with my current progress.
menu.components.ts import { Component, OnInit, Injectable } from '#angular/core'; import { FilterArrayPipe } from '../shared/pipes/filter.pipe'; #Component({ selector: 'appc--menu', templateUrl: './menu.component.html', providers: [FilterArrayPipe] }) export class MenuComponent implements OnInit { constructor(private pipe: FilterArrayPipe) { } ngOnInit() { } // todo: get data from a service data: any = [{ "name": "Trade", "children": [{ "name": "May 2013", "children": [{ "name": "2013-05-12 Project X", "children": [] }] }, { "name": "October 2013", "children": [{ "name": "2013-10-12 Visualization project", "children": [] }] }, { "name": "September 2013", "children": [{ "name": "2013-09-12 Angular project", "children": [] }] }] }, { "name": "Logistics", "children": [{ "name": "April 2014", "children": [{ "name": "2014-04-14 Party fun project", "children": [] }] }, { "name": "November 2014", "children": [{ "name": "2014-11-01 Random project", "children": [] }, { "name": "2014-11-03 Arbitrary project", "children": [] }, { "name": "2014-11-14 Fun project", "children": [] }] }, { "name": "October 2014", "children": [{ "name": "2014-10-01 Another fun project", "children": [] }, { "name": "2014-10-03 Typing excercise", "children": [] }, { "name": "2014-10-05 No project", "children": [] }, { "name": "2014-10-07 Well paid project", "children": [] }, { "name": "2014-10-08 Even more awesome project", "children": [] }] }, { "name": "September 2014", "children": [{ "name": "2014-09-14 Last project", "children": [] }] }] }]; filteredData: any = (this.data); updateFilteredData = (newVal: string) => { alert(newVal); var filtered = (this.data); filtered = filtered.map((lvl_1) => { lvl_1.children = lvl_1.children.map((lvl_2) => { lvl_2.children = this.pipe.transform(lvl_2.children, newVal); return lvl_2; }); return lvl_1; }); this.filteredData = filtered.filter((lvl_1) => { lvl_1.children = lvl_1.children.filter((lvl_2) => { return lvl_2.children.length > 0; }); return lvl_1.children.length > 0; }); } } filter.pipe.ts import { Pipe, PipeTransform } from '#angular/core'; #Pipe({ name: 'filter' }) export class FilterArrayPipe { transform(value, args) { if (value && args && args != '') { if (!args[0]) { return value; } else if (value) { return value.filter(item => { for (let key in item) { if ((typeof item[key] === 'string' || item[key] instanceof String) && (item[key].toUpperCase().indexOf(args.toUpperCase()) !== -1)) { return true; } else if ((typeof item[key] === 'number' || item[key] instanceof Number) && (item[key].toString().indexOf(args) !== -1)) { return true; } } }); } } return value; } } menu.component.html <div> Welcome to the menu component! <input type="search" #query (keyup)="updateFilteredData(query.value)" placeholder="Search..." /> <ul *ngFor="let lvl1 of filteredData "> <li> <h1>{{lvl1.name}}</h1> <ul *ngFor="let lvl2 of lvl1.children "> <li> <h3>{{lvl2.name}}</h3> <ul *ngFor="let lvl3 of lvl2.children "> <li> <p>{{lvl3.name}}</p> </li> </ul> </li> </ul> </li> </ul> </div>
How to check the checkboxes for allready exist in array id's in angular:
I have a simple array of objects: pickedFeeds = [ { "id": "1", "name": "ALLEN Production Lake", "status": "IN_PROGRESS", "owner": "ih546q" }, { "id": "2", "name": "Demo Lake", "status": "IN_PROGRESS", "owner": "ih546q" } ] And then i have a list of "feeds" like this: feeds:[{ id:1, name:'ALLEN Production Lake' },{ id:2, name:'Demo Lake' }, { id:3, name:'mamalake' }, { id:4, name:'tatalake' }, { id:5, name:'mapalake' }, { id:6, name:'gagalake' }, { id:7, name:'ramalake' }, { id:8, name:'chakalake' }, { id:9, name:'dumdumlake' }, { id:10, name:'popolake' }] }; on the last list i have a checkboxes on them: <div ng-repeat='feed in feeds'> <input type="checkbox" id='{{feed.id}}'/> <label for='{{feeds.id}}' class='lake-name'>{{feed.name}}<span class='checkbox-input-style'></span></label> I want to do the following: i want to check[V] the ones who are allready in the pickedfeeds array, when i uncheck i want to remove, if exist from the list of pickedFeeds and so forth.. How should i do so? what is my ng-model should be?
You can create function to check if in pickedFeeds exist element with this same id as feed.id ie: $scope.test = function(feed){ if(filterFilter($scope.pickedFeeds,{id:feed.id} ).length >0) { return true; } } and after that you can add to your view : <input type="checkbox" id='{{feed.id}}' ng-model="feed.checked" ng-checked="test(feed)" /> Just don't forget to add dependency on filterFilter to you controller. Please see demo below: var app = angular.module('app', []); app.controller('homeCtrl', function($scope, filterFilter) { $scope.test = function(feed) { if (filterFilter($scope.pickedFeeds, { id: feed.id }).length > 0) { return true; } } $scope.pickedFeeds = [{ "id": "1", "name": "ALLEN Production Lake", "status": "IN_PROGRESS", "owner": "ih546q" }, { "id": "2", "name": "Demo Lake", "status": "IN_PROGRESS", "owner": "ih546q" }] $scope.feeds = [{ id: 1, name: 'ALLEN Production Lake' }, { id: 2, name: 'Demo Lake' }, { id: 3, name: 'mamalake' }, { id: 4, name: 'tatalake' }, { id: 5, name: 'mapalake' }, { id: 6, name: 'gagalake' }, { id: 7, name: 'ramalake' }, { id: 8, name: 'chakalake' }, { id: 9, name: 'dumdumlake' }, { id: 10, name: 'popolake' }] }); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="homeCtrl"> <div ng-repeat='feed in feeds'> <input type="checkbox" id='{{feed.id}}' ng-model="feed.checked" ng-checked="test(feed)" /> <label for='{{feeds.id}}' class='lake-name'>{{feed.name}}<span class='checkbox-input-style'></span> </label> </div> </div>