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

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>

Related

Filtering on a formatted datefield

I've started recently with AngularJS, and I've come across this problem.
I'm filtering a list with a Angular Filter object. It all works, but I want to be able to type a date value to filter the date column. Problem is, the date that comes from my webservice is (ofcourse) in another format than the showed date.
Here is an example:
View:
Name: <input type="text" ng-model="search.Name"><br>
Date: <input type="text" ng-model="search.Date"><br>
<table>
<tr ng-repeat="item in filtered = (list | filter:search)">
<td>{{item.Name}}</td>
<td>{{item.Date | date:'dd-MM-yyyy'}}</td>
</tr>
</table>
Controller:
app.controller('MainCtrl', function($scope) {
$scope.list = [{
Name: "Item1",
Date: "2018-08-06T13:43:11.82Z"
},{
Name: "Item2",
Date: "2018-08-05T13:43:11.82Z"
},{
Name: "Item3",
Date: "2018-08-04T13:43:11.82Z"
},{
Name: "Item4",
Date: "2018-08-03T13:43:11.82Z"
}
];
$scope.search = {};
$scope.$watch('search', function (newVal, oldVal) {
$scope.filtered = filterFilter($scope.list, newVal);
}, true);
});
working example:
http://plnkr.co/edit/O7j1DAzoxArHK4mnjyeP?p=info
How can I alter this, so I can type the date-value as formatted?
At this case you should create custom filter:
angular.module('plunker', []).controller('MainCtrl', function($scope) {
$scope.list = [{
Name: "Item1",
Quantity: 21,
Date: "2018-08-06T13:43:11.82Z"
}, {
Name: "Item2",
Quantity: 20,
Date: "2018-08-05T13:43:11.82Z"
}, {
Name: "Item3",
Quantity: 31,
Date: "2018-08-04T13:43:11.82Z"
}, {
Name: "Item4",
Quantity: 25,
Date: "2018-08-03T13:43:11.82Z"
}];
$scope.search = {};
}).filter('custom', function() {
return function(array, search) {
function Norm(x) {
return (x + '').toLocaleLowerCase();
}
return array.filter(function(x) {
for (var prop in search) {
if (prop != 'Date' && search[prop] &&
Norm(x[prop]).indexOf(Norm(search[prop])) == -1)
return false;
}
if (x.Date) {
var formatted = x.Date.substring(0, 10).split('-').reverse().join('-');
if (search.Date && !formatted.startsWith(search.Date))
return false;
return true;
}
});
}
});
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<body ng-app='plunker' ng-controller="MainCtrl">
Name: <input type="text" ng-model="search.Name">
<br> Quantity: <input type="text" ng-model="search.Quantity">
<br> Date: <input type="text" ng-model="search.Date">
<br>
<table>
<tr ng-repeat="item in list | custom : search | orderBy : 'Quantity'">
<td>{{item.Name}}</td>
<td>{{item.Quantity}}</td>
<td>{{item.Date | date:'dd-MM-yyyy'}}</td>
</tr>
</table>
</body>
Html:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS</title>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
Name:
<input type="text" ng-model="search.Name">
<br>
Date:
<input type="text" ng-model="search.Date">
<table>
<tr ng-repeat="item in list2 | filter : search.Date">
<td>{{item.Name}}</td>
<td>{{item.Date}}</td>
</tr>
</table>
</body>
</html>
Js:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $filter) {
const list = [{
Name: "Item1",
Date: "2018-08-06T13:43:11.82Z"
},{
Name: "Item2",
Date: "2018-08-05T13:43:11.82Z"
},{
Name: "Item3",
Date: "2018-08-04T13:43:11.82Z"
},{
Name: "Item4",
Date: "2018-08-03T13:43:11.82Z"
}
];
$scope.list2 = list.map(x => (
{
Name: x.Name,
Date: $filter('date')(x.Date, 'dd-MM-yyyy')
})
);
});

use angular.js to get data from a web endpoint

I need to use angular in order to get data from a web endpoint to fill this table. I have a list created with random names, but I need it to filled with data from a link instead. I still need to create the social media links as well.
Either way, can someone show me how to do it keeping in mind that I don't know much about angular at all. thank you.
html:
<!DOCTYPE html>
<html>
<head>
<title>Angular JS </title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script type="text/javascript" src="folder/main.js"></script>
<script src="http://code.angularjs.org/1.4.8/angular.js"></script>
<script src="http://code.angularjs.org/1.4.8/angular-resource.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body ng-app="MyForm">
<div ng-controller="myCtrl">
<h3>List students</h3>
<div class="container-fluid">
<pre>Click header link to sort, input into filter text to filter</pre>
<hr />
<table class="table table-striped">
<thead>
<tr>
<th>Edit</th>
<th>
ID
</th>
<th> Name </th>
<th>Social Media </th>
</tr>
</thead>
<tbody>
<tr>
<td>Filter =>></td>
<td> <input type="text" ng-model="search.name" /></td>
<td> <input type="text" ng-model="search.age" /> </td>
<td><input type="text" ng-model="search.gender" /> </td>
</tr>
<tr ng-repeat="user in students | orderBy:predicate:reverse | filter:paginate| filter:search" ng-class-odd="'odd'">
<td>
<button class="btn">
Edit
</button>
</td>
<td>{{ user.name}}</td>
<td>{{ user.age}}</td>
<td>{{ user.gender}}</td>
</tr>
</tbody>
</table>
<pagination total-items="totalItems" ng-model="currentPage"
max-size="5" boundary-links="true"
items-per-page="numPerPage" class="pagination-sm">
</pagination>
</div>
</div>
</body>
</html>
js:
<script>
var app = angular.module('MyForm', ['ui.bootstrap', 'ngResource']);
app.controller('myCtrl', function ($scope) {
$scope.predicate = 'name';
$scope.reverse = true;
$scope.currentPage = 1;
$scope.order = function (predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
$scope.students = [
{ name: 'Kevin', age: 25, gender: 'boy' },
{ name: 'John', age: 30, gender: 'girl' },
{ name: 'Laura', age: 28, gender: 'girl' },
{ name: 'Joy', age: 15, gender: 'girl' },
{ name: 'Mary', age: 28, gender: 'girl' },
{ name: 'Peter', age: 95, gender: 'boy' },
{ name: 'Bob', age: 50, gender: 'boy' },
{ name: 'Erika', age: 27, gender: 'girl' },
{ name: 'Patrick', age: 40, gender: 'boy' },
{ name: 'Tery', age: 60, gender: 'girl' }
];
$scope.totalItems = $scope.students.length;
$scope.numPerPage = 5;
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.students.indexOf(value);
return (begin <= index && index < end);
};
});
</script>
the data looks like this:
{"id":"11","name":"A Cooperativa","full_address":"Rua Bar\u00e3o de Viamonte 5, 2400-262 Leiria","location":"Leiria","council":"Leiria","country":"Portugal","lat":"39.7523042","lng":"-8.7825576","type":"various","facebook":"https:\/\/www.facebook.com\/pages\/A-Cooperativa-MerceariaTasca\/1559630810945570","facebook_id":"","gmaps":"https:\/\/www.google.pt\/maps\/place\/R.+Bar%C3%A3o+de+Viamonte+5,+2410+Leiria\/#39.7523042,-8.7825576,17z\/data=!3m1!4b1!4m2!3m1!1s0xd2273a29462db11:0x49a3f9a45cd9eb80","tripadvisor":"http:\/\/www.tripadvisor.com\/Restaurant_Review-g230085-d8154189-Reviews-A_Cooperativa-Leiria_Leiria_District_Central_Portugal.html","zomato":"","website":"","email":"cooperativa.tasca#hotmail.com","telephone":"912635324","active":"1","updated":"2015-08-17 09:01:05"}
I'm not sure if I did get this right, but:
You want to get the students from a web endpoint as json?
Then you would write something like this in angular:
app.controller('myCtrl', function ($scope, $http) {
...
$scope.students = [];
$scope.totalItems = 0;
$http.get('https://www.domain.com/api/resource')
.then(function success(response) {
$scope.students = response.data;
$scope.totalItems = $scope.students.length;
}, function failed(reason) {console.log(reason);})
...
});
But you should use separated files, services etc.

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 search using two criterions( select and input)

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'}"

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