AngularJS disable dropdown option which previously selected - javascript

var demoApp = angular.module('myApp', []);
demoApp.controller('QaController', function($scope, $http) {
$scope.loopData = [{}, {}];
$scope.questions = {
model: null,
availableOptions: [
{id: '1', name: 'What is your childhood name?'},
{id: '2', name: "What is your first school?"},
{id: '3', name: "What is your first job place?"},
{id: '4', name: "What is your pet name?"}
]
};
$scope.submit = function() {
$scope.result = $scope.loopData;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div class="wrapper wrapper-content middlealigen col-sm-12" ng-controller="QaController">
<form ng-submit="submit();">
<div ng-repeat="x in loopData">
<h5>Q. {{$index + 1}}</h5>
<select class="form-control" name="question-drop" id="question_dropdown" ng-model="x.question" ng-options="option.id as option.name for option in questions.availableOptions">
<option value="">Select Question</option>
</select>
<input type="text" placeholder="Enter Answer" name="answer" class="form-control" ng-model="x.answer" />
<div class="m-b"></div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div ng-if="result">
<pre>{{result | json}}</pre>
</div>
</div>
</body>
Can you please check my code snippet. Here is two dropdown.
If I select What is your childhood name? from Q. 1 dropdown then this option should be disabled in the Q. 2 dropdown. How can I do that?

var demoApp = angular.module('myApp', []);
demoApp.controller('QaController', function($scope, $http) {
$scope.loopData = [];
$scope.loopData = [{
model: null,
question : "",
availableOptions: [
{id: '1', name: 'What is your childhood name?',disable : false},
{id: '2', name: "What is your first school?",disable : false},
{id: '3', name: "What is your first job place?",disable : false},
{id: '4', name: "What is your pet name?",disable : false}
]
},{
model: null,
question : "",
availableOptions: [
{id: '1', name: 'What is your childhood name?',disable : false},
{id: '2', name: "What is your first school?",disable : false},
{id: '3', name: "What is your first job place?",disable : false},
{id: '4', name: "What is your pet name?",disable : false}
]
}]
$scope.changItem = function(index,_id){
$scope.loopData = $scope.loopData.map(function(obj,i){
debugger
if(i > index){
obj.availableOptions.map(function(item){
if(item.id == _id ){
item.disable = true
}else{
item.disable = false
}
return item
})
}else{ debugger
obj.availableOptions.map(function(item){
debugger
if(item.id == _id ){
item.disable = true
}else{
item.disable = false
}
return item
})
}
return obj
});
}
$scope.submit = function() {
$scope.result = $scope.loopData;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div class="wrapper wrapper-content middlealigen col-sm-12" ng-controller="QaController">
<form ng-submit="submit();">
<div ng-repeat="x in loopData track by $index">
<h5>Q. {{$index + 1}}</h5>{{x.modelVal}}
<select
ng-change="changItem($index,x.question)" ng-model="x.question" >
<option value="">Select Question</option>
<option ng-disabled="option.disable" ng-repeat="option in x.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
<input type="text" placeholder="Enter Answer" name="answer" class="form-control" ng-model="x.answer" />
<div class="m-b"></div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div ng-if="result">
<pre>{{result | json}}</pre>
</div>
</div>
</body>

You might create a custom filter to be more generic (for more select inputs).
The filter could be:
.filter('excludeEqualAnswers', function() {
return function(input, index, selectedQuestions) {
if (!selectedQuestions[index].question) {
function notExistInSelectedQuestions(output) {
return !selectedQuestions.map(val => val.question).includes(output.id);
}
return input.filter(notExistInSelectedQuestions);
} else {
return input
}
}
})
Then you can filter the options of your select input based upon your custom filter like this:
<select class="form-control" name="question-drop" id="question_dropdown" ng-model="x.question" ng-options="option.id as option.name for option in questions.availableOptions | excludeEqualAnswers:$index:loopData">
<option value="">Select Question</option>
</select>
Here's a working fiddle

Related

Vuejs rendering select dropdown based on first choice in first drop down

I have two drop-down menus. Depending on the choice of the first drop-down the choices of the second need to be filtered and displayed. The first dropdown has a RoomID value that is used to filter an array of objects for the second drop-down menu. When I select a Room in the first dropdown the console log shows the correct data for the second dropdown. however, it is not rendering in the Html. I am not sure why this is not working
Html:
<div id="reports-menu" class="myTextColor1 pl-10">
<div class="row">
<div class="input-field col s12">
<select v-model="selectedRoomID">
<option disabled selected>Rooms</option>
<option v-for="room in rooms" v-bind:value="room.RoomID">{{room.Room}}</option>
</select>
<label>Room:</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select v-model="selectedTopicID">
<option disabled selected>Topics</option>
<option v-for="option in selectedRoom" v-bind:value="option.TopicID">{{option.Topic}}</option>
</select>
<label>Topic:</label>
</div>
</div>
</div>
JS:
var data = <%=return_message%>;
let arrRooms = _.uniqBy(data, function (e) {
return e.Room;
});
let arrTopics = _.uniqBy(data, function (e) {
return e.Topic;
});
let arrDps = _.uniqBy(data, function (e) {
return e.DiscussionPoint;
});
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, {});
});
var chatReportsMenuComponent = new Vue({
el: "#reports-menu",
created: function () {
document.getElementById("reports-menu").style.display = "block";
//GET TOPIC INFO - PASS TOPIC PARAM;
this.initialize();
},
data: {
selectedRoomID: undefined,
rooms:arrRooms,
selectedTopicID: undefined,
topics:arrTopics,
dps:arrDps
},
methods: {
initialize: function () {
var self = this;
}
},
computed:{
selectedRoom: function(){
var filteredTopics = _.filter(arrTopics,{'RoomID': this.selectedRoomID})
console.log("Filterd Topics: ", filteredTopics)
return filteredTopics
}
}
})
I've simplified your code for the sake of ease, but see the below example on how to achieve this (if i've understood your question correctly):
new Vue({
el: "#app",
data() {
return {
selectedRoom: null,
rooms: [
{name: 'room 1', topicId: 1},
{name: 'room 2', topicId: 2},
{name: 'room 3', topicId: 3}
],
topics: [
{id: 1, name: 'topic 1', options: ['one', 'two', 'three']},
{id: 2, name: 'topic 2', options: ['four', 'five', 'six']},
{id: 3, name: 'topic 3', options: ['seven', 'eight', 'nine']}
],
selectedTopicOption: null,
}
},
computed:{
selectedRoomTopic() {
const selected = this.selectedRoom
return (selected)
? this.topics.find(x => x.id === selected.topicId)
: null
}
}
})
<div id="app">
<label>Select a room</label>
<select v-model="selectedRoom">
<option disabled selected>Rooms</option>
<option v-for="room in rooms" :value="room">
{{ room.name }}
</option>
</select>
<div v-if="selectedRoomTopic">
<label>Select a Topic</label>
<select v-model="selectedTopicOption">
<option disabled selected>Topics</option>
<option v-for="option in selectedRoomTopic.options" :value="option">
{{option}}
</option>
</select>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

Unable to set selected option in dropdown control

I am unable to bind selected option in dropdown control. I don't want whole object of $scope.Types inside $scope.obj. It should just have value of $scope.Types inside $scope.obj.type
var app = angular.module("myApp", []);
app.controller("MyController", function($scope) {
$scope.types =
[
{ label: "Pizza", value: 1 },
{ label: "Cakes", value: 2 },
{ label: "Pastry", value: 3 }
];
$scope.obj = { type : 1 };//I want dropdown selected value to be updated in type variable
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="MyController">
<select name="status" ng-model="obj.value"
ng-options="type.value as type.label for type in types track by type.value">
<option value="">Select Types</option>
</select>
</ul>
I am not getting what wrong I am doing here.
var app = angular.module("myApp", []);
app.controller("MyController", function($scope) {
$scope.obj = {};
$scope.types =
[
{ label: "Pizza", value: 1 },
{ label: "Cakes", value: 2 },
{ label: "Pastry", value: 3 }
];
$scope.obj.value = 2;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="MyController">
<select name="status" ng-model="obj.value"
ng-options="type.value as type.label for type in types">
<option value="">Select Types</option>
</select>
</ul>
Like this?
var app = angular.module("myApp", []);
app.controller("MyController", function($scope) {
$scope.$watch('selectedValue', function(newValue, oldValue) {
if (newValue){
$scope.obj.type = newValue.value;
}
});
$scope.types =
[
{ label: "Pizza", value: 1 },
{ label: "Cakes", value: 2 },
{ label: "Pastry", value: 3 }
];
$scope.obj = { type: 1 };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="MyController">
<select name="status" ng-model="selectedValue"
ng-options="type as type.label for type in types track by type.value">
<option value="">Select Types</option>
</select>
{{ obj.type}}
</ul>

VueJS access model from method

In VueJS I am setting model data based on user actions. I want to access the model from a method to update an element.
In the code below, when the user changes the first select list, I want to update the second select list to show the id property of the first list. As it is the upper list works OK but the lower list id property is not updated on upper list change:
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>
</head>
<body>
<div id="editor">
<form id="query" methods="GET">
<div id="form_container" class="row">
<div class="form-group">
<label for="choice-selector">Choices</label>
<select class="form-control" id="choice-selector" v-model="choice_id" v-on:change="refreshOptions">
<option v-for="item in choices" v-bind:value="item.id">
{{ item.name }}
</option>
</select>
<span>Current choice id: {{ choice_id }}</span>
<br>
<label for="option-selector">Options</label>
<select class="form-control" id="option-selector" v-model="option_id" >
<option v-for="item in options" v-bind:value="item.id">
{{ item.name }}
</option>
</select>
<span>Current option id: {{ option_id }}</span>
</div>
</div>
</div>
<script>
let index = 0;
new Vue({
el: '#editor',
data: {
choice_id: '1',
choices: [
{ id: '1', name: 'Choice A' },
{ id: '2', name: 'Choice B' },
{ id: '3', name: 'Choice C' }
],
option_id: '1',
options: [
]
},
ready: function startFetch() {
this.refreshOptions();
},
methods: {
refreshOptions: function refreshOptionList() {
console.log(">>refreshOptionList() index:" + index);
const vm = this;
const newOptions = [{ id: index, name: 'Option based on choices list id: ' + vm.choice_id }];
vm.$set('options', newOptions);
index += 1;
}
},
});
</script>
</body>
</html>
Any ideas?
In Vue 2.x vm.$set is an alias for Vue.set and it takes 3 parameters: target, key and value so you should use it like this:
vm.$set(this, 'options', newOptions);
Or you can just assign newOptions to this.options
this.options = newOptions;
Working example: https://plnkr.co/edit/lFDm7wxb56h81EAwuUNc

data-ng-model and data-ng-change are not working with data-ng-selected

var appCompAssets = angular.module('app.company.assets', []);
appCompAssets.controller('locationDetailCTRL', function($scope, $http) {
// LOAD LOCATION DETAILS
$scope.loadBranches = function() {
$http.get('../getBranches_id_name/' + $scope.compid)
.then(
function(response) {
if (response.data.length !== 0) {
$scope.getBranches_id_name = response.data;
console.log($scope.getBranches_id_name);
}
},
function(response) {
// error handling routine
console.log('$Error: no data for branch id & name');
});
};
$scope.loadLocations = function(branch_id) {
$scope.branchid = branch_id;
$http.get('../getLocations_id_name/' + $scope.branchid)
.then(
function(response) {
if (response.data.length !== $scope.branchid) {
$scope.getLocations_id_name = response.data;
console.log($scope.getLocations_id_name);
}
},
function(response) {
// error handling routine
console.log('$Error: no data for location id & name');
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-ng-app="app.company.assets" data-ng-controller="locationDetailCTRL">
<div class="row" data-ng-init="loadBranches()">
<div class="col-sm-12">
<div class="form-group">
<label for="branch_id" class="small"><i>Branch</i>
</label>
<select class="form-control input-sm" data-ng-init="loadLocations(assetInfo.branch_id)" data-ng-change="loadLocations(assets.branch_id)" id="branch_id" name="branch_id" data-ng-model="assets.branch_id">
<option data-ng-selected="assetInfo.branch_name ===b.branch_name" data-ng-repeat="b in getBranches_id_name" value="{{b.id}}">{{b.branch_name}}</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="location_id" class="small"><i>Location</i>
</label>
<select class="form-control input-sm" id="location_id" name="location_id">
<option value=""></option>
<option data-ng-repeat="l in getLocations_id_name" value="{{l.id}}" data-ng-selected="l.location_name == assetInfo.location_name">{{l.location_name}}</option>
</select>
</div>
</div>
</div>
</div>
Guys, I am having problem with making data-ng-selected, data-ng-model and data-ng-change work at the same time.
if without the data-ng-model and data-ng-change
the data-ng-selected is working fine.
Excluded data-ng-model and data-ng-change and remain only data-ng-selected, the output is as below:
Although, it is able to display the value wanted, when changing the branch(dropdown), the location(s) for the respective branch won't change since there are no ng-change and ng-model exist.
However, if with all the above mentioned data-ng attribute together(data-ng-model,ng-change and ng-selected), it will not display properly as the branch is not selected which it supposed to be selected. The output is as below:
for changing the branch and the location will change, that part is working fine.
Your kind assistance will be appreciated. Thank you!.
The response result on the top is for branch and the one at the bottom is for location. Thank you.
try like this, hope it helps , let me know in case you are looking for something different.
Plunker : http://plnkr.co/edit/VE5ja2kkV9Xp7og1CkAl?p=preview
in script
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.branches = [
{ id: 1, name: 'Testing Branch 1'},
{ id: 2, name: 'Testing Branch 2'},
{ id: 3, name: 'Testing Branch 3'}
];
$scope.locations = [
{ id: 1, branchId: 1, name: 'Office Room 1'},
{ id: 2, branchId: 1, name: 'Office Room 2'},
{ id: 3, branchId: 2, name: 'Office Room 3'},
{ id: 4, branchId: 3, name: 'Office Room 4'}
];
$scope.loadLocations = function(branchId) {
console.log('Selected BranchId: ' + branchId);
};
// for selecting options on page load set the model for both the select
$scope.selectedBranchId = 2;
$scope.selectedLocationId = 3;
});
in view.
<body ng-controller="MainCtrl">
<h1>Cascading DropDownList</h1>
<hr />
<h4>Branch</h4>
<select ng-options="branch.id as branch.name for branch in branches"
ng-model="selectedBranchId"
ng-change="loadLocations(selectedBranchId)">
<option value="">Select Branch</option>
</select>
<h4>Location</h4>
<select ng-options="location.id as location.name for location in locations | filter: { branchId: selectedBranchId }"
ng-model="selectedLocationId"
ng-disabled="!selectedBranchId">
<option value="">Select Location</option>
</select>
</body>
What you need is a cascading dropdown list, well your html code seems complex to me for what you're trying to achieve.
You can simplify it as follows.
angular
.module("demo", [])
.controller("DefaultController", DefaultController);
function DefaultController() {
var vm = this;
vm.branches = [
{ id: 1, name: 'Testing Branch 1' },
{ id: 2, name: 'Testing Branch 2' },
{ id: 3, name: 'Testing Branch 3' }
];
vm.locations = [
{ id: 1, branchId: 1, name: 'Office Room 1' },
{ id: 2, branchId: 1, name: 'Office Room 2' },
{ id: 3, branchId: 2, name: 'Office Room 3' },
{ id: 4, branchId: 3, name: 'Office Room 4' }
];
vm.loadLocations = loadLocations;
// set data
getData();
function loadLocations(branchId) {
// load locations here when branch is changed.
// if locations are loaded only when a branch is selected
// then you can remove the filter in ng-options for Location
console.log('Selected BranchId: ' + branchId);
};
function getData() {
// get data via AJAX here and set the selected options in the view via data binding (ngModel)
var data = {
branch: {
id: 3,
name: 'Testing Branch 3'
},
location: {
id: 4,
branchId: 3,
name: 'Office Room 4'
}
};
vm.branch = data.branch.id;
vm.location = data.location.id;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<h1>Cascading DropDownList</h1>
<hr />
<h4>Branch</h4>
<select ng-options="branch.id as branch.name for branch in ctrl.branches"
ng-model="ctrl.branch"
ng-change="ctrl.loadLocations(ctrl.branch)">
<option value="">Select Branch</option>
</select>
<h4>Location</h4>
<select ng-options="location.id as location.name for location in ctrl.locations | filter: { branchId: ctrl.branch }"
ng-model="ctrl.location"
ng-disabled="!ctrl.branch">
<option value="">Select Location</option>
</select>
</div>
</div>
<div class="row" data-ng-init="loadBranches()">
<div class="col-sm-12">
<div class="form-group">
<label for ="branch_id" class="small"><i>Branch</i></label>
<select class = "form-control input-sm"
data-ng-options="b.id as b.branch_name for b in getBranches_id_name" data-ng-init="branch_id = assetInfo.branch_id" data-ng-model="branch_id"
data-ng-change="loadLocations(branch_id)" id="branch_id"
name="branch_id"></select>
</div>
</div>
</div>
<div class="row" data-ng-init="loadLocations(branch_id)">
<div class="col-sm-12">
<div class="form-group">
<label for ="location_id" class="small"><i>Location</i></label>
<select class = "form-control input-sm"
data-ng-options="l.id as l.location_name for l in getLocations_id_name"
id="location_id" name="location_id" data-ng-init="location_id = assetInfo.location_id" data-ng-model="location_id" data-ng-disabled="!branch_id" ></select>
</div>
</div>
</div>
Hi #Deep and #abdul mateen mohammed, with the above code, it works as i wanted, however, there is a problem, i could not save the value to the database (the value of the selected option is not saved to the database).
But with the code below, i can save the value to the database but it won't work as i wanted which by default it will pre-load the branch and location when on load. The only changes i made is by adding the "track by" in the ng-option.
<div class="row" data-ng-init="loadBranches()">
<div class="col-sm-12">
<div class="form-group">
<label for ="branch_id" class="small"><i>Branch</i></label>
<select class = "form-control input-sm"
data-ng-options="b.id as b.branch_name for b in getBranches_id_name track by b.id" data-ng-init="branch_id = assetInfo.branch_id" data-ng-model="branch_id"
data-ng-change="loadLocations(branch_id)" id="branch_id"
name="branch_id"></select>
</div>
</div>
</div>
<div class="row" data-ng-init="loadLocations(branch_id)">
<div class="col-sm-12">
<div class="form-group">
<label for ="location_id" class="small"><i>Location</i></label>
<select class = "form-control input-sm"
data-ng-options="l.id as l.location_name for l in getLocations_id_name track by l.id"
id="location_id" name="location_id" data-ng-init="location_id = assetInfo.location_id" data-ng-model="location_id" data-ng-disabled="!branch_id" ></select>
</div>
</div>
</div>
Your kind assistance will be appreciated. Thank you.
#Deep, this is how i saved the data to database. Thank you.
IN THE CONTROLLER:
function update() {
$this->model->update($_POST);
}
IN THE MODEL:
function update($data) {
$assetid = $data['assetid'];
unset($data['assetid']); // remove #assetid element from the array #data
$this->db->update('assets', $data, "`id` = {$assetid}");
}

Filtering array based on selected checkboxes and select fields

How can I store the selected values of checkboxes and select elements and use a combination of these to filter a results array? e.g. think filtering by category Id, or displaying all results in the last X months.
After much research and trial and error I've got as far as this:
View Plunker or see the code below:
HTML within the 'refine' directive
<div class="filters">
<div class="filter">
<label for="maxage">Show results from</label>
<select name="maxage" id="maxage"
ng-options="option.name for option in refine.maxAge.options track by option.id"
ng-model="refine.maxAge.selected"
ng-change="filterResults()">
</select>
</div>
<div class="filter">
<div class="status-filter" ng-repeat="status in refine.statuses">
<label for="statusId{{ status.id }}">{{ status.name }}</label>
<input type="checkbox" name="status" value="{{ status.id }}" ng-change="filterResults()">
</div>
</div>
</div>
HTML of main page
<body ng-app="app">
<div ng-controller="ListCtrl" data-county-parish-id="1478">
...
<main class="page-content columns medium-9 medium-push-3">
...
<spinner name="planningSpinner" show="true">
<div class="loadingPanel block"></div>
</spinner>
<div class="planning">
<div class="no-results ng-hide" ng-show="filteredResults.length === 0">
<p>No results.</p>
</div>
<h4>Number of records: {{ filteredResults.length }}</h4>
<div ng-repeat="appl in filteredResults">
<hf-application info="appl"></hf-application>
</div>
</div>
...
</main>
<aside class="sidebar columns medium-3 medium-pull-9">
...
<div hf-refine-results info="refine"></div>
</aside>
...
</div>
</body>
JS
var app = angular.module('app', []);
// results filter
angular.module('app').filter('results', ['$filter', function($filter) {
return function (input, refine) {
var filterParams = {};
// start off filtering with the outsideBoundary parameter
filterParams.outsideBoundary = refine.outsideBoundary;
// add 'show results from' filter
//var adjustedDate = new Date();
//adjustedDate.setMonth(adjustedDate.getMonth() - refine.maxAge.selected.id);
//filterParams.receivedDate = $filter('date')(adjustedDate, 'yyyy/MM/dd');
return $filter('filter')(input, filterParams);
}
}]);
// Controller
angular.module('app').controller('ListCtrl',
['$scope', '$filter', '$attrs', 'appService', 'resultsFilter', function ($scope, $filter, $attrs, appService, resultsFilter) {
$scope.applications = [];
$scope.refine = {
statuses: {
options: [
{ id: 1, name: 'Unknown' },
...
{ id: 6, name: 'Appealed' }
],
selected: [2, 3]
},
maxAge: {
options: [
{ id: '1', name: 'Last month' },
... // 1 to 12 months
{ id: '12', name: 'Last 12 months' }
],
selected: { id: '6', name: 'Last 6 months' }
},
...
};
$scope.filterResults = function () {
$scope.filteredResults = resultsFilter($scope.applications, $scope.refine);
};
/* get data from appService */
appService.getApplications({
status: 3,
countyparish: parseInt($attrs.countyParishId),
postcode: '',
distance: 5,
pagesize: 100
})
.then(function (data) {
$scope.applications = data;
$scope.filteredResults = resultsFilter(data, $scope.refine);
});
}]);
I appreciate this question has been asked many times, however I haven't found an answer for my question(s) since most examples are very simple expressions within ng-repeat.
This example work with multi checkbox. For filtering with outher select use same logic. Look
'use strict';
var App = angular.module('clientApp', ['ngResource', 'App.filters']);
App.controller('ClientCtrl', ['$scope', function ($scope) {
$scope.selectedCompany = [];
$scope.companyList = [{
id: 1,
name: 'Apple'
}, {
id: 2,
name: 'Facebook'
}, {
id: 3,
name: 'Google'
}];
$scope.clients = [{
name: 'Brett',
designation: 'Software Engineer',
company: {
id: 1,
name: 'Apple'
}
}, {
name: 'Steven',
designation: 'Database Administrator',
company: {
id: 3,
name: 'Google'
}
}, {
name: 'Jim',
designation: 'Designer',
company: {
id: 2,
name: 'Facebook'
}
}, {
name: 'Michael',
designation: 'Front-End Developer',
company: {
id: 1,
name: 'Apple'
}
}, {
name: 'Josh',
designation: 'Network Engineer',
company: {
id: 3,
name: 'Google'
}
}, {
name: 'Ellie',
designation: 'Internet Marketing Engineer',
company: {
id: 1,
name: 'Apple'
}
}];
$scope.setSelectedClient = function () {
var id = this.company.id;
if (_.contains($scope.selectedCompany, id)) {
$scope.selectedCompany = _.without($scope.selectedCompany, id);
} else {
$scope.selectedCompany.push(id);
}
return false;
};
$scope.isChecked = function (id) {
if (_.contains($scope.selectedCompany, id)) {
return 'icon-ok pull-right';
}
return false;
};
$scope.checkAll = function () {
$scope.selectedCompany = _.pluck($scope.companyList, 'id');
};
}]);
angular.module('App.filters', []).filter('companyFilter', [function () {
return function (clients, selectedCompany) {
if (!angular.isUndefined(clients) && !angular.isUndefined(selectedCompany) && selectedCompany.length > 0) {
var tempClients = [];
angular.forEach(selectedCompany, function (id) {
angular.forEach(clients, function (client) {
if (angular.equals(client.company.id, id)) {
tempClients.push(client);
}
});
});
return tempClients;
} else {
return clients;
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular-resource.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css">
<div ng-app="clientApp" data-ng-controller="ClientCtrl">
<ul class="inline">
<li>
<div class="alert alert-info">
<h4>Total Filtered Client: {{filtered.length}}</h4>
</div>
</li>
<li>
<div class="btn-group" data-ng-class="{open: open}">
<button class="btn">Filter by Company</button>
<button class="btn dropdown-toggle" data-ng-click="open=!open"><span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu">
<li><a data-ng-click="checkAll()"><i class="icon-ok-sign"></i> Check All</a>
</li>
<li><a data-ng-click="selectedCompany=[];"><i class="icon-remove-sign"></i> Uncheck All</a>
</li>
<li class="divider"></li>
<li data-ng-repeat="company in companyList"> <a data-ng-click="setSelectedClient()">{{company.name}}<span data-ng-class="isChecked(company.id)"></span></a>
</li>
</ul>
</div>
</li>
</ul>
<hr/>
<h3>Clients Table:</h3>
<table class="table table-hover table-striped">
<thead>
<tr>
<th style="width:10%">#</th>
<th style="width:20%">Name</th>
<th style="width:40%">Designation</th>
<th style="width:30%">Company</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="client in filtered = (clients | companyFilter:selectedCompany)">
<td>{{$index + 1}}</td>
<td><em>{{client.name}}</em>
</td>
<td>{{client.designation}}</td>
<td>{{client.company.name}}</td>
</tr>
</tbody>
</table>
</div>

Categories

Resources