Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to trigger AngularJS ng-show

Tags:

angularjs

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).

like image 530
Sovos Avatar asked Dec 16 '12 13:12

Sovos


People also ask

What can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

Which is the correct syntax of AngularJS directive ng-show?

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.

Can we use ng-show and Ng hide together?

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.

What is the difference between Ng-click and Onclick?

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.


1 Answers

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()
like image 69
tocallaghan Avatar answered Sep 19 '22 03:09

tocallaghan