Hi Guys,
You can create a directive to implement search functionality and can show suggestions.
In the below implementation you can find how it works.
In html you have to add search directive
The directive controller has friend list on which we have to do searching.
Using angularjs filter you can iterate over json.You can create a directive to implement search functionality and can show suggestions.
In the below implementation you can find how it works.
In html you have to add search directive
<ng-search></ng-search>
The directive controller has friend list on which we have to do searching.
$scope.searchItem = $filter("filter")($scope.friends, text, false);
Whenever user press any key in textbox it calls controller function and generate result in searchItem.
$scope.searching = function(text){ if(''!=text){ $scope.searchItem = $filter("filter")($scope.friends, text, false); }else{ $scope.searchItem = []; } }
The directive generate suggestion box using searchItem.-----------------------
<div class="outerDiv"> <input ng-change="searching(searchText)" ng-model="searchText" type="text" /> <br /> <div class="searchDiv" ng-repeat="obj in searchItem"&{{obj.name}}</div>
You can find implementation code below
index.html
<html ng-app="simpleDirective"> <head> <script src="angular.min.js"></script> <script src="app.js"></script> </head> <body style="margin:10;padding:0;"> <div style="margin:0 auto"> <div style="text-align: center">Searching demo</div> <ng-search></ng-search> </body> </html>
app.js
var app = angular.module('simpleDirective', []); app.directive("ngSearch", function(){ return{ restrict:"E", controller: function($scope, $filter){ $scope.friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}, {name:'Juliette', phone:'555-5678'}]; $scope.searchText; $scope.searching = function(text){ if(''!=text){ $scope.searchItem = $filter("filter")($scope.friends, text, false); }else{ $scope.searchItem = []; } } }, template:"<div class="outerDiv"> <input ng-change="searching(searchText)" ng-model="searchText" type="text" /> <br /> <div class="searchDiv" ng-repeat="obj in searchItem">{{obj.name}}</div> </div> " } });
styling
Good Day :)
1 Comments
I am building a small search app using AngularJS and Elasticsearch. I'm using AngularJS UI Bootstrap Typeahead for autocomplete functionality. Now I'm trying to create a custom search directive for the search functionality. Still learning AngularJS directives...
ReplyDeleteI should just be able to add the UI Bootstrap Typeahead directive to this custom search directive, right? (as an attr).
So I would just need to pass the suggestion function, search function and search terms (ng-model) to my custom search directive?