ElenaDBA ElenaDBA - 1 year ago 92
AngularJS Question

AngularJS text suggestion textbox

I am working on text suggestion textbox using angularjs.

Below is my page html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app>
<script type="text/javascript" src="Scripts/angular.js"></script>
<script type="text/javascript" src="Scripts/angular-mocks.js"></script>
<script type="text/javascript" src="BaseCtrl.js"></script>
<body ng-controller="BaseController">
<div class="input-group" style="width: 50%;">
<input type="text" class="form-control" id="FirstName" ng-model="fnamequery" ng-change="toggleSuggest()">
<p ng-repeat="fname in fnames | filter:fnamequery">{{fname}}</p>


and here is my controller file BaseCtrl.js:

angular.module('TextApp',[]).controller('BaseController', function($scope, $http) {
$scope.fnames = ["Aida", "Aidan", "Alla", "Allen", "Beverly", "Bea", "Caleb", "Catherine"];
$scope.toggleSuggest = function () {
if ($scope.fnamequery == '') $('p').hide();
else $('p').show();

In the future I am planning to pull up the names from the database via Web API call, but for now I am just trying to get it to work with hard-coded values.

Now I get all the values shown on the page. The values do get filtered out as I type something in but initially everything gets displayed

Answer Source

You are using $('p').hide() and $('p').show() to hide/show DOM elements which looks more like jQuery methods to me. Your code sample is throwing this error :

ReferenceError: $ is not defined at Object.MyCtrl.$scope.toggleSuggest

Angular's ng-show or ng-hide directives should do the trick in this case :

<body ng-controller="BaseController">
    <div class="input-group" style="width: 50%;">
        <input type="text" ng-model="fnamequery">
        <p ng-repeat="fname in fnames | filter:fnamequery" ng-hide="fnamequery==''">{{fname}}</p>


function BaseController($scope, $http) {
    $scope.fnamequery = '';
    $scope.fnames = ["Aida", "Aidan", "Alla", "Allen", "Beverly", "Bea", "Caleb","Catherine"];

Here is a working jsFiddle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download