I wanted my search box to search using tags which I have illustrated below with the image. I have tried using bootstrap tags it doesn't work for me.
This is how my search should look like
I wanted my search box to search using tags which I have illustrated below with the image. I have tried using bootstrap tags it doesn't work for me.
This is how my search should look like
On
Check this fiddle:
https://jsfiddle.net/elmacko/hu2yngat/55/
You can change the filter to fit your needs. Also, this can be ofcourse be refined further but it will give you an idea of how it could be done.
angular.module("app", [])
.directive("badgeSearch", function()
{
return {
restrict: "E",
replace: true,
template: `
<div class='badge-search-container'>
<a href='#' ng-click='removeBadge($index)'
class='badge badge-primary search-badge'
ng-repeat='badge in badges track by $index'>{{ badge }}
</a>
<form class='badge-search-form'>
<input class='badge-search-input' type='text'
ng-model='search'>
<button class='btn btn-primary' type='submit'
ng-click='addBadge()'>
Add
</button>
</form>
</div>`,
controller: "badgeSearchController",
scope: {},
link: function(scope, element, attributes)
{
scope.badges = [];
scope.search = "";
if(attributes.ngModel)
{
scope.modelController = element.controller("ngModel");
scope.modelController.$isEmpty = function(value)
{
return !value || value.length === 0;
};
scope.modelController.$render = function()
{
scope.badges = scope.modelController.$viewValue;
};
}
}
};
})
.controller("badgeSearchController", function($scope)
{
$scope.addBadge = function()
{
if($scope.search)
{
$scope.badges.push($scope.search);
$scope.search = "";
}
};
$scope.removeBadge = function(index)
{
$scope.badges.splice(index, 1);
// This will trigger ng-change to fire, even in cases where $setViewValue() would not.
angular.forEach($scope.modelController.$viewChangeListeners, function(listener) {
try {
listener();
} catch (e) {
this.$exceptionHandler(e);
}
});
};
})
.filter("badgeFilter", function()
{
return function(items, badges)
{
if(!badges || !badges.length)
{
return items;
}
return items.filter(function(item)
{
return badges.indexOf(item) != -1;
});
};
})
.controller("mainController", function($scope)
{
$scope.items = [
"first",
"second"
];
$scope.badges = [];
});
html
<div ng-app="app" ng-controller="mainController">
<badge-search ng-model="badges"></badge-search>
<ul class="list-group">
<li ng-repeat="item in items | badgeFilter:badges" class="list-group-item">{{ item }}</li>
</ul>
</div>
css
.badge-search-input
{
height: 100%;
border: 0px;
outline: none;
}
.badge-search-form
{
display: inline-block;
}
.badge-search-container
{
padding-left: 8px;
height: 39px;
margin: 16px;
border: 1px solid black;
border-radius: 0px 4px 4px 0px;
}
.search-badge
{
margin-right: 8px;
}
Use the ngTagsInput directive:
link
https://github.com/mbenford/ngTagsInput