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