<!doctype html>
<html ng-app="searchModule">
<head>
<meta charset="utf-8">
<title>Angular Live Search</title>
<link rel="stylesheet" href="styles.css">
</head>
<body ng-controller="searchController">
<h1>Angular Live Search</h1>
<!-- Search -->
<input type="text" placeholder="Search" ng-model="query" ng-focus="focus=true">
<div id="search-results" ng-show="focus">
<div class="search-result" ng-repeat="item in data | search:query" ng-bind="item" ng-click="setQuery(item)"></div>
</div>
<!-- Load JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<script src="data.js"></script>
<script src="app.js"></script>
</body>
</html>
body {
color: #333;
font-family: Arial, Calibri, sans-serif;
}
input {
width: 280px;
height: 40px;
color: #333;
font-size: 16px;
padding: 5px;
border: 1px solid #dedede;
border-radius: 3px;
box-sizing: border-box;
}
#search-results {
width: 280px;
max-height: 200px;
border: 1px solid #dedede;
border-radius: 3px;
box-sizing: border-box;
overflow-y: auto;
}
.search-result {
background: white;
padding: 10px;
}
.search-result:nth-child(even) {
background: #fafafa;
}
var app = angular.module('searchModule', []);
// Defines the search controller by bringing the data into the scope.
//
app.controller('searchController', function($scope) {
$scope.data = data;
$scope.setQuery = function(query) {
$scope.query = query;
$scope.focus = false;
};
});
// Returns the search function that will perform the filter on the data.
//
app.filter('search', function() {
return search;
});
// Returns an array of items where the item text matches the search query. In
// this example, both the query and item are converted to lower case for easier
// matching.
//
function search(arr, query) {
if (!query) {
return arr;
}
var results = [];
query = query.toLowerCase();
angular.forEach(arr, function(item) {
if (item.toLowerCase().indexOf(query) !== -1) {
results.push(item);
}
});
return results;
};
var data = [
'AngularJS',
'C',
'C++',
'C#',
'CoffeeScript',
'CSS',
'Go',
'HTML',
'Jade',
'Java',
'JavaScript',
'LESS',
'Node.js',
'Objective-C',
'Sass/SCSS',
'Stylus',
'Swift'
];