how to search using two criterions( select and input) - angularjs

i'm new in angular js , and i'm trying to search in a my table , using a selectbox.
I want that my search will be based on two xriterion: ( what i will write on the input item , and on what i will select )
for exemple if i will select ( search by name ) , i should search just based on name:
here is my code :
<div ng-controller="mycontrolleur">
<input type='text' ng-model="searchT">
<select ng-model="choix">
<option value='nom'>search by name</option>
<option value='cin'>search by CIN</option>
</select>
<table border="1">
<tr><td>Nom</td><td>CIN</td></tr>
<tr ng-repeat="x in students|filter:searchT|orderBy:choix">
<td>{{x.nom}} </td><td>{{x.cin}}</td></tr>
</table>
</div>
<script src='angular.min.js'></script>
<script>
var app=angular.module('searchApp',[]);
app.controller('mycontrolleur',function($scope)
{
$scope.students=[{nom:'marwen',cin:11155},
{nom:'mounir',cin:15885},
{nom:'maryem',cin:25155},
{nom:'ahmed',cin:77555},
{nom:'amel',cin:88155}
];
});
</script>
thank you for your help guys :)

You can use a filter like this one :
app.filter('filterByCustomProp', function($filter) {
return function(source, prop, searchValue) {
if (!searchValue) return source;
if (!prop) return $filter('filter')(source, searchValue); //search on name & CIN
return source.filter(function(item) {
return (item[prop].toString().indexOf(searchValue) > -1);
});
};
});
Then you can call :
<tr ng-repeat="x in students|filterByCustomProp:choix:searchT|orderBy:choix">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="searchApp" ng-controller="mycontrolleur">
<input type='text' ng-model="searchT">
<select ng-model="choix">
<option value='nom'>search by name</option>
<option value='cin'>search by CIN</option>
</select>
<table border="1">
<tr>
<td>Nom</td>
<td>CIN</td>
</tr>
<tr ng-repeat="x in students|filterByCustomProp:choix:searchT|orderBy:choix">
<td>{{x.nom}}</td>
<td>{{x.cin}}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('searchApp', []);
app.filter('filterByCustomProp', function($filter) {
return function(source, prop, searchValue) {
if (!searchValue) return source;
if (!prop) return $filter('filter')(source, searchValue); //search on name & CIN
return source.filter(function(item) {
return (item[prop].toString().indexOf(searchValue) > -1);
});
};
});
app.controller('mycontrolleur', function($scope) {
$scope.students = [{
nom: 'marwen',
cin: 11155
}, {
nom: 'mounir',
cin: 15885
}, {
nom: 'maryem',
cin: 25155
}, {
nom: 'ahmed',
cin: 77555
}, {
nom: 'amel',
cin: 88155
}];
});
</script>

Hello you can use filter by object. For example:
ng-repeat="client in clients | filter: {name: 'Brett', designation: '1'}"

Related

Angular js - How to do strict and progressive search on same field?

I'm trying to do strict and progressive search on same fields in 2 different ways. That is when filter through drop down it should to a strict search and through input search it should do a progressive search. I tried to do it using <tr ng-repeat="x in names | filter:{name:name||dropdownFieldName:true, country:country}"> but is giving some error, Its not working.
Please check the bellow code and help me to solve this issue
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<select id="fieldDropdownHtml" ng-model="fieldSelected" ng-options="x.name for x in names" ng-change="searchOnField()">
<option value=""></option>
</select>
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr>
<td><p><input type="text" ng-model="name" ng-disabled="disablese"></p>
<td><p><input type="text" ng-model="country"></p>
</td>
</tr>
<tr ng-repeat="x in names | filter:{name:name||dropdownFieldName, country:country}">
<!--tr ng-repeat="x in names | filter:{name:name||dropdownFieldName:true, country:country}" -->
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.disablese = false;
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Jani1',country:'England'},
{name:'Jani',country:'Norway'}
];
$scope.searchOnField = function() {
var e = document.getElementById("fieldDropdownHtml");
var strUser = e.options[e.selectedIndex].text;
angular.forEach($scope.names, function(dsElement) {
if (dsElement.name === strUser) {
$scope.dropdownFieldName = dsElement.name;
console.log($scope.dropdownFieldName);
}
if(document.getElementById('fieldDropdownHtml').selectedIndex == 0){
$scope.dropdownFieldName= undefined;
}
if(document.getElementById('fieldDropdownHtml').selectedIndex != 0){
$scope.disablese = true;
$scope.name = "";
}
else{
$scope.disablese = false;
}
});
}
});
</script>
</body>
</html>
Additional to Allabakash answer, you can use this code to your controller to make it simpler and minimize vanilla JavaScript codes:
angular
.module('myApp', [])
.controller('namesCtrl', function ($scope) {
$scope.disablese = false;
$scope.names = [
{ name: 'Jani', country: 'Norway' },
{ name: 'Carl', country: 'Sweden' },
{ name: 'Margareth', country: 'England' },
{ name: 'Hege', country: 'Norway' },
{ name: 'Joe', country: 'Denmark' },
{ name: 'Gustav', country: 'Sweden' },
{ name: 'Birgit', country: 'Denmark' },
{ name: 'Jani1', country: 'England' },
{ name: 'Jani', country: 'Norway' }
];
$scope.searchOnField = function () {
if ($scope.fieldSelected) {
$scope.dropdownFieldName = $scope.fieldSelected.name;
$scope.name = null;
$scope.disablese = true;
} else {
$scope.dropdownFieldName = undefined;
$scope.disablese = false;
}
};
});
You can achieve this by separating filters like below.
ng-repeat="x in names | filter:{name:name||dropdownFieldName}: disablese | filter: { country:country }"
Hope this helps.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<select id="fieldDropdownHtml" ng-model="fieldSelected" ng-options="x.name for x in names" ng-change="searchOnField()">
<option value=""></option>
</select>
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr>
<td><p><input type="text" ng-model="name" ng-disabled="disablese"></p>
<td><p><input type="text" ng-model="country"></p>
</td>
</tr>
<tr ng-repeat="x in names | filter:{name:name||dropdownFieldName}: disablese | filter: { country:country }">
<!--tr ng-repeat="x in names | filter:{name:name||dropdownFieldName:true, country:country}" -->
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.disablese = false;
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Jani1',country:'England'},
{name:'Jani',country:'Norway'},
{name:'Jani',country:'Harway'}
];
$scope.searchOnField = function() {
var e = document.getElementById("fieldDropdownHtml");
var strUser = e.options[e.selectedIndex].text;
angular.forEach($scope.names, function(dsElement) {
if (dsElement.name === strUser) {
$scope.dropdownFieldName = dsElement.name;
console.log($scope.dropdownFieldName);
}
if(document.getElementById('fieldDropdownHtml').selectedIndex == 0){
$scope.dropdownFieldName= undefined;
}
if(document.getElementById('fieldDropdownHtml').selectedIndex != 0){
$scope.disablese = true;
$scope.name = "";
}
else{
$scope.disablese = false;
}
});
}
});
</script>
</body>
</html>

AngularJS : ng-model not working in multiple drop down

I am trying to create dynamic rows based on button click. The rows have drop down boxes. The issue is when I add new row and select an option in the new row the options which I selected in previous rows are also changing, I mean the previous rows options are not binding properly.
My HTML code :
<div id="features" ng-controller="featuresCtrl">
<br>
<div class="row">
<div class="form-group col-md-6">
<table cellpadding="15" cellspacing="10">
<thead>
<tr>
<th style="text-align: center;">Feature</th>
<th style="text-align: center;">Type</th>
<th style="text-align: center;">Value</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr></tr>
<tr ng-repeat="r in rows">
<td>
<select ng-model="r.data.model" ng-options="option.name for option in data.availableOptions"
ng-change="getValues(r.data.model.name)">
<option value="">Select Feature</option>
</select>
</td>
<td>
<select ng-model="r.updateData.model" ng-options="option.name for option in updateData.availableOptions"
ng-change="getBinSet(r.updateData.model.name)">
<option value="">Select Type</option>
</select>
</td>
<td>
<select ng-model="r.binData.model" ng-options="option.name for option in binData.availableOptions">
<option value="">Select Value</option>
</select>
</td>
<td ng-if="showAdd">
<div class="text-center">
<button ng-click="addRow()">Add</button>
</div>
</td>
<td ng-if="showAdd">
<div class="text-center">
<button ng-click="remove($index)">Remove</button>
</div>
</td>
</tr>
<tr>
<td></td>
<td style="align-self: center;">
<button style="align-self: center" ng-click="submitForm(rows)">Submit</button>
</td>
<td></td>
</tr>
</tbody>
</table>
<br>
</div>
My angular JS code :
'use strict';
var testControllers = angular.module('testControllers');
testControllers.controller('featuresCtrl', ['$scope','$route','$filter', '$http', '$location','$window','$timeout', 'NgTableParams',
function($scope, $route, $filter, $http, $location, $window, $timeout, NgTableParams) {
$scope.rows = [{}];
$scope.nrows = [];
$scope.showAdd = false;
$scope.addRow = function() {
$scope.rows.push({
});
};
$scope.remove = function(index) {
$scope.rows.splice(index, 1);
};
$scope.submitForm = function(rows) {
console.log("rows", rows);
};
$scope.data = {
model: null,
availableOptions: [
{ name: 'TestA'},
{ name: 'TestB'},
{ name: 'TestC'},
{ name: 'TestD'}
]
};
$scope.getValues = function (featureType) {
console.log("getValues", featureType);
$scope.showAdd = false;
if (featureType != null) {
$http.get('/getPropensityValues.do', {params: {'featureType': featureType}}).success(function (data) {
var test = [];
angular.forEach(data, function (item) {
test.push({name: item});
});
$scope.updateData = {
model: null,
availableOptions : test
};
});
}
};
$scope.getBinSet = function (featureType) {
console.log("getBinSet", featureType);
$scope.showAdd = true;
if (featureType != null) {
$scope.binData = {
model: null,
availableOptions: [
{name: '1'},
{name: '2'},
{name: '3'},
{name: '4'},
{name: '5'},
{name: '6_10'},
{name: '10_15'},
{name: '16_20'},
{name: '21_25'},
{name: '26_30'},
{name: '31_35'},
{name: '36_40'},
{name: '41_45'},
{name: '46_50'},
{name: '>50'}
]
};
}
};
}]);
Can some one tell me what I am doing wrong here ? I tried with another example - https://plnkr.co/edit/Jw5RkU3mLuGBpqKsq7RH?p=preview
Even here I am facing same issue when selecting the 2nd row 1st row also changing. Is it wrong to use r.data.model to bind each row's values ?
I updated your plunker to work:
https://plnkr.co/edit/4sJHHaJPEuYiaHjdnFBp?p=preview
You weren't defining what the model was when you were redefining the options menus (side note: you should leverage underscore.js's difference function within a filter to create the appropriate display options dynamically)
Anyway, in your addRow() function, I changed it from this:
if(val=== 'TestB') {
$scope.data1 = {
model: null,
availableOptions: [
{ name: 'TestA'},
{ name: 'TestC'},
{ name: 'TestD'}
]
};
}
to this:
if(val=== 'TestB') {
$scope.data1 = {
model: 'TestB',
availableOptions: [
{ name: 'TestA'},
{ name: 'TestC'},
{ name: 'TestD'}
]
};
}
Let me know if this helps
UPDATE:
I recreated the functionality from scratch because I think you were overthinking things. All that is needed here is very simple ng-repeat, ng-options, and ng-model bindings.
<tr ng-repeat="r in rows track by $index">
<td>
<select ng-model="r.name"
ng-options="option.name as option.name for option
in availableOptions">
<option value="">Select Value</option>
</select>
</td>
<td>
<input type="button" ng-click="addRow()" value="Add">
</td>
<td>
<input type="button" ng-click="deleteRow($index)"
value="Delete">
</td>
</tr>
and for the angular
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.rows = [{name:""}];
$scope.addRow = function(){
$scope.rows.push({name:""});
}
$scope.availableOptions = [
{ name: 'TestA'},
{ name: 'TestB'},
{ name: 'TestC'},
{ name: 'TestD'}
];
$scope.deleteRow = function(index){
$scope.rows.splice(index,1);
}
});
I didn't throw in the difference thing yet, but it should be easy.

How to filter a row in AngularJS based on data in a particular 'td'

I have a table made in AngularJS and I am trying to learn SortBy and Filter options.
I want to sort the table based on data in a particular TD. I don't want to filter by inputting a filter manually, but I want to hardcode that filter to the table.
My current table is :
<table ng-table="talentPoolList" show-filter="true" class="table table-striped table-bordered">
<tr ng-repeat="employee in data | filter: testFilter">
<td data-title="'#'">{{$index + 1}}</td>
<td data-title="'First Name'" sortable="'employee.employee.firstName'" filter="{ 'employee.employee.firstName': 'text' }">
{{employee.employee.firstName}}
</td>
<td data-title="'Last Name'" sortable="'employee.employee.lastName'" filter="{ 'employee.employee.lastName': 'text' }">
{{employee.employee.lastName}}
</td>
<td data-title="'Current State'" sortable="'currentState'" filter="{ 'currentState': 'text' }">
{{employee.state.state}}
</td>
<td data-title="'Reserve to (state):'" ng-if="employee.state.state == 'Available' ">
<select>
<option disabled selected value> -- select an option -- </option>
<option id="123">123</option>
<option id="234">234</option>
<option id="345">345</option>
<option id="456">456</option>
<option id="567">567</option>
</select>
</td>
</tr>
</table>
In the above table, I want the filtering to be done based on the :
<td data-title="'Current State'" sortable="'currentState'" filter="{ 'currentState': 'text' }">
{{employee.state.state}}
</td>
{{employee.state.state}} returns several values. They can be any one of the following :
1. Available
2. Resigned
3. OnNotice
4. Blocked
5. Accepted
6. Rejected
7. Shadow
I want the table to only display the states Available and Blocked..
My Controller is:
'use strict';
angular.module('employeeTalentPool', []);
//Routers
myApp.config(function ($stateProvider) {
$stateProvider.state('employeeTalentPool', {
url: '/employeeTalentPool',
templateUrl: 'partials/talentPoolEmployees/employeeTalentPool.html',
data: {
auth: true
}
});
});
//Factories
myApp.factory('employeeTalentPoolServices', ['$http', function ($http) {
var factoryDefinitions = {
//getAllBenchers: function () {
// return $http.get(myApp.TalentPoolBaseUrl + '/EmployeeState?state=Available&pageNumber=1&pageSize=5').success(function (data) { return data; });
// },
getAllBenchers: function () {
return $http.get(myApp.TalentPoolBaseUrl + '/EmployeeState?state=&pageNumber=0&pageSize=0').success(function (data) { return data; });
},
reserveEmployee: function () {
return $http.post('').success(function (data) { return data;});
}
}
return factoryDefinitions;
}
]);
//Controllers
myApp.controller('getAllBenchersController', ['$scope', 'employeeTalentPoolServices', function ($scope, employeeTalentPoolServices) {
employeeTalentPoolServices.getAllBenchers().then(function (result) {
$scope.data = result.data;
$scope.testFilter = function (item) {
return (item.state.state.toLowerCase() === 'available' || item.state.state.toLowerCase() === 'rejected');
}
});
}]);
Can anyone help me with creating a hard coded filter in the table that will show only those two states?
Thank You
angular.module("testApp", [])
.controller("testController", function testController($scope) {
$scope.data = [{
state: {
state: 'Available'
}
}, {
state: {
state: 'Available'
}
}, {
state: {
state: 'Misc'
}
}, {
state: {
state: 'Rejected'
}
}, {
state: {
state: 'Available'
}
}, {
state: {
state: 'Abc'
}
}, ];
$scope.testFilter = function(item) {
return (item.state.state.toLowerCase() === 'available' || item.state.state.toLowerCase() === 'rejected');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-table="talentPoolList" show-filter="true" class="table table-striped table-bordered" ng-controller="testController" ng-app="testApp">
<tr ng-repeat="employee in data | filter: testFilter">
<td>{{employee.state.state}}</td>
</tr>
</table>
<tr ng-repeat="employee in data | filter: {state: 'Available'}">
The simplest way to do this is like above.
You can also write your own filter, as shown in the snippet

How to use an array on ng-model

This is my code http://plnkr.co/edit/oxtojjEPwkKng9iKkc14?p=preview
And I want to save object of sport and punctuation in an array, if there are one or more sports selected save it in the array like this:
likes[
{sport: 'futball', points: 1}, {sport: 'tennis', points: 1}
]
thanks!
You have to keep practicing your English a little bit more (you can ask me on the comment section in spanish if you are strugling)
I think what you are trying to do is to have a single select to be able to choose the sport and score,
Html:
<body ng-app="myapp">
<div class="main-container" ng-controller="main" ng-init="darr.dept=dept2">
<div class="client-area">
<label fo.table-container tabler="txt">Score</label>
<input type="text" id="name-txt" placeholder="Assign the score" ng-model="name">
<br />
Sport
<select ng-model="dept" ng-options="deptOpt.value as deptOpt.name for deptOpt in deptList"></select>
<br />
<button ng-click="add()">Add Item</button>
<table id="tab">
<thead>
<tr id="trow">
<th>Score</th>
<th>Sport</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="ar in arr">
<td>{{ar.name}}</td>
<td>{{ar.dept}}</td>
<td>
<button ng-click="del($index)">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
js:
var app = angular.module("myapp", []);
app.controller('main', function ($scope) {
$scope.arr = [];
$scope.deptList = [{
name: 'Football',
value: 'football'
}, {
name: 'Tennis',
value: 'Tennis'
}, {
name: 'Baseball',
value: 'baseball'
}];
$scope.dept = "football";
$scope.name = "";
$scope.add = function () {
this.arr.push({
name: this.name,
dept: this.dept
});
};
$scope.del = function (ind) {
this.arr = this.arr.splice(ind, 1);
};
$scope.editStudent = function(student) {
console.log(student);
};
});
https://jsfiddle.net/azweig/v5kbsudy/1

how to reset a filter by leaving it empty?

I have a filter on a list :
<input ng-model="searchFileName" />
<table>
<tr ng-repeat="file in folders | filter:searchFileName">
<td><a ng-click="openFolder(file.name)">{{ file.name }}</a></td>
</tr>
</table>
I would like to clear searchFileName value when I click on a result.
This is openFolder function :
$scope.openFolder = function(name) {
$scope.searchFileName = null;
$http.jsonp($scope.server + '?open=' + encodeURIComponent($scope.buildTreePath()) + '&callback=JSON_CALLBACK').success(function(data){
$scope.folders = data;
});
}
}
I can't empty my filter field, it doesn't work... Where am I wrong ?
just use:
$scope.openFolder = function(name) {
$scope.searchFileName = null;
}
var app = angular.module('app', []);
app.controller('fCtrl', function($scope) {
$scope.folders = [
{
name: "Ala"
}, {
name: "Ata"
}, {
name: "Ara"
}, {
name: "Ama"
}
];
$scope.openFolder = function(name) {
$scope.searchFileName = null;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="fCtrl">
<input ng-model="searchFileName" />
<table>
<tr ng-repeat="file in folders | filter:searchFileName">
<td><a ng-click="openFolder(file.name)">{{ file.name }}</a>
</td>
</tr>
</table>
</div>
</div>

Resources