I'm building an autocomplete box in AngularJS. The relevant code looks like this
<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>
I'd like to know what is the best way to show the list of suggestions when "tag" has no value (i.e. I want to show all the tags when the user press the down key. No need to mention the keypressing code on the answer).
You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.
AngularJS ng-show Directive The ng-show directive shows the specified HTML element if the expression evaluates to true, otherwise the HTML element is hidden.
Absolutely not. First of all, the two directives can trip over each other( see this JSFiddle, as provided by Joel Skrepnek), and is generally just bad design.
Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.
ng-show works with any expression that results in a bool, so all you need to do is replace "tag" with "tag === ''", or some equivalent if your tag is going to be undefined or null.
If you only want to show when a certain key is pressed I would create another variable which you set to true when the down key is pressed and check for that also, e.g.
$scope.KeyPressed = false;
$scope.Tags = '';
$scope.ShowTags = function () {
return $scope.KeyPressed && $scope.Tags !== '';
};
Then in you div:
<div ng-show="ShowTags()">
See jsfiddle for example
If you need to change any of the variables from within a jquery plugin you may need to use
$scope.$apply()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With