In this article, you will learn how to implement ngTagsInput directive in AngularJS. We will use Web API to get the data from SQL Server database with Entity Framework.
What is a tags input?
A tags input is an input box that automatically creates tags – also called tokens – out of typed text every time a certain key is pressed. It's useful for tagging and highlighting information right on the input box.
What is ngTagsInput?
ngTagsInput is a highly customizable tags input directive built for the AngularJS framework, with no external dependencies. It provides a <tags-input> element so you can semantically express you're using an input with tagging capabilities.
Where should I use it?
You can benefit from an input with tagging support when you want to let users enter tags for a post, select multiples contacts from a list, or any other situation where it's appropriate to have an inline, as-you-type list of items.
Stored Procedure
- USE [NORTHWND]
- GO
-
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- ALTER PROCEDURE [dbo].[GetEmployee]
- AS
- SELECT EmployeeID,
- FirstName,
- LastName,
- City,
- Region,
- PostalCode,
- Country,
- Notes
- FROM Employees
- ORDER BY EmployeeID DESC
Web API – Let’s work on Web API part first:
Model Class:
- public partial class GetEmployee_Result
- {
- public int EmployeeID { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string City { get; set; }
- public string Region { get; set; }
- public string PostalCode { get; set; }
- public string Country { get; set; }
- public string Notes { get; set; }
- }
Builder Class:-
-
-
-
- public async Task<IEnumerable<GetEmployee_Result>> GetEmployee()
- {
- try
- {
- return await db.Database.SqlQuery<GetEmployee_Result>("GetEmployee").ToListAsync();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
Web API- [RoutePrefix("api/EmployeeAPI")]
- public class EmployeeAPIController : ApiController
- {
- private readonly EmployeeVMBuilder _employeeVMBuilder = new EmployeeVMBuilder();
-
- [Route("GetEmployee")]
- public async Task<IEnumerable<GetEmployee_Result>> GetEmployee()
- {
- return await _employeeVMBuilder.GetEmployee();
- }
- }
Thus, we are done with Entity framework and API Controller here. Now, install the files given below, using "Manage NuGet Package".
Add JavaScript files and CSS reference in BundleConfig.cs.
- bundles.Add(new StyleBundle("~/Content/css").Include(
- "~/Content/bootstrap.css",
- "~/Content/site.css",
- "~/Content/ui-grid.min.css",
- "~/Content/ng-tags-input.css"));
- bundles.Add(new ScriptBundle("~/bundles/angular").Include(
- "~/Scripts/angular.js",
- "~/Scripts/angular-route.js",
- "~/Scripts/ui-grid.js",
- "~/Scripts/angular-ui/ui-bootstrap.js",
- "~/Scripts/angular-ui/ui-bootstrap-tpls.js"));
- bundles.Add(new ScriptBundle("~/bundles/ngtagsInput").Include(
- "~/Scripts/ng-tags-input.js"));
- bundles.Add(new ScriptBundle("~/bundles/employee").Include(
- "~/Angular/app.js",
- "~/Angular/Services/employeeService.js",
- "~/Angular/Controller/employeeController.js",
- "~/Angular/Controller/editEmployeeController.js",
- "~/Angular/Controller/addEmployeeController.js",
- "~/Angular/Controller/ngtagsInputController.js"));
And, render on _layout.cshtml.- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- @Scripts.Render("~/bundles/angular")
- @Scripts.Render("~/bundles/employee")
- @Scripts.Render("~/bundles/ngtagsInput")
- @RenderSection("scripts", required: false)
Now, add a new Angular Controller with scope. I am using just one script for Module, Service, and Controller. You can have it separate if working on a big project. Module
-
- var app = angular.module('app', ['ngRoute',
- 'ui.grid',
- 'ui.grid.edit',
- 'ui.grid.pagination',
- 'ui.grid.autoResize',
- 'ui.grid.expandable',
- 'ui.grid.selection',
- 'ui.grid.pinning',
- 'ui.bootstrap',
- 'ngTagsInput'])
- .config(function ($routeProvider, $locationProvider) {
- $locationProvider.hashPrefix('');
- $routeProvider
- .when('/', {
- templateUrl: 'Home',
- controller: 'homeController'
- })
- .when('/employee', {
- templateUrl: 'Employee',
- controller: 'employeeController'
- });
- });
Service
- app.service('employeeService', function ($http) {
-
- this.getEmployees = function () {
- var req = $http.get('api/EmployeeAPI/GetEmployee');
- return req;
- };
- });
Controller
- app.controller("ngtagsInputController", function (
- $scope, $filter,
- employeeService, $window,
- $http, $log, $interval, $uibModal, $q) {
-
- $scope.tags = [];
- $scope.employees = [];
-
-
- employeeService.getEmployees().then(function (result) {
- angular.forEach(result.data, function (value, index) {
- $scope.employees.push({ id: value.EmployeeID, name: value.FirstName + " " + value.LastName });
- });
- console.log($scope.employees);
- }, function (error) {
- $window.alert('Something went wrong while fetching the employee data.');
- });
-
- $scope.loadEmployees = function($query)
- {
- var myemployees = $scope.employees;
- return myemployees.filter(function(employee) {
- return employee.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
- });
- }
-
- });
Index
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <h2>ngTagInput Sample</h2>
- <div ng-controller="ngtagsInputController">
- <tags-input ng-model="tags" display-property="name" placeholder="Add a employee" replace-spaces-with-dashes="false">
- <auto-complete source="loadEmployees($query)"
- min-length="1"
- load-on-focus="false"
- load-on-empty="false"
- max-results-to-show="32"
- template="my-custom-template"></auto-complete>
- </tags-input>
- <p>Selected Model: {{tags}}</p>
- <script type="text/ng-template" id="my-custom-template">
- <div class="right-panel">
- <span ng-bind-html="$highlight($getDisplayText())"></span>
- </div>
- </script>
- </div>
As everything is done, run the application.
Type some keyword in textbox.
As you can see data is auto populate based on keyword, and whatever keyword you entered that is highlighted.
After selection you selection you can see that is added in textbox with remove option.
Conclusion
In this article, we have seen how to implement AutoComplete text box with Web API and Entity Framework in MVC. If you have any questions or comments, drop me a line in the comments section.