我正在使用angularjs处理文本建议文本框。
下面是我的页面html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app>
<head>
<title></title>
<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>
</head>
<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>
</div>
</body>
</html>
这是我的控制器文件 BaseCtrl.js:
angular.module('TextApp',[]).controller('BaseController', function($scope, $http) {
$scope.fnames = ["Aida", "Aidan", "Alla", "Allen", "Beverly", "Bea", "Caleb", "Catherine"];
$scope.toggleSuggest = function () {
console.log($scope.fnamequery);
if ($scope.fnamequery == '') $('p').hide();
else $('p').show();
}
});
将来,我计划通过 Web API 调用从数据库中提取名称,但现在我只是尝试让它使用硬编码值。
现在我得到了页面上显示的所有值。当我输入内容时,这些值确实会被过滤掉,但最初所有内容都会显示
您正在使用$('p').hide()
和$('p').show()
来隐藏/显示DOM元素,这对我来说更像jQuery方法。您的代码示例抛出此错误:
ReferenceError: $ 未在 Object.MyCtrl.$scope.toggleSuggest 中定义
在这种情况下,Angular 的 ng-show
或 ng-hide
指令应该可以解决问题:
<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>
</div>
</body>
控制器:
function BaseController($scope, $http) {
$scope.fnamequery = '';
$scope.fnames = ["Aida", "Aidan", "Alla", "Allen", "Beverly", "Bea", "Caleb","Catherine"];
}
这是一个工作 jsFiddle。