AngularJS ng - show one condition with multiple elements

I have three ng-click divs with "showMe" buffer. There is an ng show in their paragraphs which speed up "showMe".

My question is, how can I use a single condition to show a paragraph on the div that I click? In other words, if I click on the first div, I should only see "1", paragraph "2" and "3" should remain hidden. ng-repeat is not an option for this exercise.

Here's the JSBin:

http://jsbin.com/kiwicipabago/1/edit

Thank.

+3


source to share


3 answers


You can do the following:

<div ng-app="app">
<div ng-controller="AppCtrl">
  <div class="box" ng-click="showMe = 1">
    <p ng-show="showMe ==1">1</p>
  </div>
  <div class="box" ng-click="showMe = 2">
    <p ng-show="showMe==2">2</p>
  </div>
  <div class="box" ng-click="showMe = 3">
    <p ng-show="showMe ==3">3</p>
  </div>
</div>

      



+7


source


All examples are in the js fiddle and go a little more in depth.

Also note that jquery is not used , I strongly recommend not using jquery in AngularJs code .
AngularJs includes jQuery lite available via the method angular.element

. You should use it for any dom manipulation if it doesn't provide you with enough functionality, then consider creating a directive.



Take a look at this controller for a deeper understanding:

app.controller("AppCtrl", ['$scope', function ($scope) {

    $scope.show_me = function (event) {
        var box = event.target.parentElement;
        var article = angular.element(box).find('article');
        var articles = angular.element(box.parentElement).find('article');
        // if already shown, hide it
        if (article.hasClass('show'))
            article.removeClass('show')
        else // elsif not shown, hide all and show it
        {
            articles.removeClass('show');
            article.addClass('show');
        }
    };

}]);

      

+1


source


Here's another solution you can use with a little jQuery:

Add to the controller a function named showMe

:

var app = angular.module("app", []);

  app.controller("AppCtrl", function($scope) {

  $scope.showMe = function(event) {
    $(event.target).find('p').toggle();
  };
});

      


And then in your HTML, change the following from:

...
<div ng-controller="AppCtrl">
  <div class="box" ng-click="showMe = !showMe">
    <p ng-show="showMe">1</p>
  </div>
</div>
...

      


in

...
<div ng-controller="AppCtrl">
  <div class="box" ng-click="showMe($event)">
    <p>1</p>
  </div>
</div>
...

      


If you want to hide the p

default elements , you can simply add some CSS:

.box p {
  display: none;
}

      


JSBin: http://jsbin.com/fegevoyoda/2/

0


source







All Articles