我正在AngularJS中构建一个自动完成框.相关代码如下所示
<input type="text" ng-model="tag">
<div ng-show="tag">
<ul>
<li ng-repeat="t in user.tags | filter:{name:tag}">
<a>{{t.name}}</a>
</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
我想知道当"标签"没有价值时显示建议列表的最佳方式是什么(即我想在用户按下向下键时显示所有标签.无需提及关键字代码回答).
toc*_*han 30
ng-show适用于导致bool的任何表达式,因此您需要做的就是将"tag"替换为"tag ===''",或者如果您的标记未定义或为null,则将其替换为等价物.
如果您只想显示何时按下某个键,我会创建另一个变量,当按下向下键时您将其设置为true并检查该变量,例如
$scope.KeyPressed = false;
$scope.Tags = '';
$scope.ShowTags = function () {
return $scope.KeyPressed && $scope.Tags !== '';
};
Run Code Online (Sandbox Code Playgroud)
然后在你div:
<div ng-show="ShowTags()">
Run Code Online (Sandbox Code Playgroud)
例如,请参阅jsfiddle
如果您需要更改jquery插件中的任何变量,则可能需要使用
$scope.$apply()
Run Code Online (Sandbox Code Playgroud)
sks*_*laj 14
我在设置自己的角度项目时遇到了这个问题.
当我做出接受的答案时,我发现我的浏览器内存不断增加.如果您创建了角度范围方法"ShowTags()",则会不断对其进行轮询.您可以通过在此方法中设置断点来验证这一点,它将不断受到影响.如果您检查任务管理器并显示运行您网站的浏览器,则内存会持续上升并且不会停止.
在我看来,范围函数只应在使用事件触发器时使用:click事件,change事件,keypressed是一些例子.
显示或隐藏不是事件,所以这就是它被调查的原因.
要修复并提供相同的功能,请将其转换为范围变量.
从以下位置更改html标记:
<div ng-show="ShowTags()">
Run Code Online (Sandbox Code Playgroud)
至
<div ng-show="ShowTags">
Run Code Online (Sandbox Code Playgroud)
在你的控制器中:
$scope.KeyPressed = false;
$scope.Tags = '';
then create a watch event on what you want to watch for:
//initialize showtag when page loads
$scope.ShowTags = $scope.KeyPressed && $scope.Tags !== '';
//watch for any new changes on keypressed
$scope.$watch('KeyPressed', function (newValue, oldValue) {
if (newValue && $scope.Tags !== '') {
$scope.ShowTags = true;
} else {
$scope.ShowTags = false;
}
}
//watch for any new changes on keypressed
$scope.$watch('Tags', function (newValue, oldValue) {
if (newValue !== "" && $scope.KeyPressed) {
$scope.ShowTags = true;
} else {
$scope.ShowTags = false;
}
}
Run Code Online (Sandbox Code Playgroud)
或者你可以改为"watchCollection",而不是像以下那样拥有多个手表:
$watchCollection('[KeyPressed, Tags]', function (newValue) { }
Run Code Online (Sandbox Code Playgroud)
但有了这个,newValue将是一个数组,你必须访问特定的索引来获取正在监视的任何变量的newValues.
比较.. newValue [0]是KeyPressed的值,newValue [1]是Tags的值
或者同意接受的答案并尽量减少手表的数量:
$scope.TruthyVal= function () {
return $scope.KeyPressed && $scope.Tags !== '';
};
$scope.$watch('TruthyVal', function (newValue, oldValue) {
if (newValue) {
$scope.ShowTags = true;
} else {
$scope.ShowTags = false;
}
}
Run Code Online (Sandbox Code Playgroud)
其中查看了KeyPressed和Tags的值,并更改了TruthyVal的值.如果改变了TruthyVal,那么它将进入观察逻辑.
| 归档时间: |
|
| 查看次数: |
52427 次 |
| 最近记录: |