AngularJS ng-show one condition with multiple elements

戏子无情 提交于 2019-12-22 10:17:34

问题


I have three divs with an ng-click with a "showMe" boolean. Their paragraphs have an ng-show that evaulates "showMe".

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

Here's a JSBin:

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

Thank you.


回答1:


You can do like this :

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




回答2:


All the examples are in this js fiddle, and a bit more elaborated.

Also, note that jquery is not used, I greatly recommend not to use jquery in your AngularJs code.
AngularJs include jQuery lite accessible by the angular.element method. You should use it for any dom manipulation, if it doesn't provide you enough functionality, then think about creating a directive.

Look at this controller for more insight:

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');
        }
    };

}]);



回答3:


Here's another solution that you can use, with the help of a little jQuery:

Add a function called showMe to your controller:

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


to:

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


If you want to hide the p elements by default, you can just add a little CSS:

.box p {
  display: none;
}


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



来源:https://stackoverflow.com/questions/25369912/angularjs-ng-show-one-condition-with-multiple-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!