Search code examples
javascriptangularjsshow-hide

Control two span tags using one function in AngularJS


I have two span tags and two p tags such as:

<span class="span1" ng-click="show()">Span_1</span>
<p class="p1" ng-show="var1">P_1</p>
<span class="span2" ng-click="show()">Span_2</span>
<p class="p2" ng-show="var1">P_2</p>

I am using AngularJS for this so what I want to achieve is to make a single function such as show() shown above to toggle the both the p tags how can i achieve that? Here is my JavaScript code:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.var1 = false;
    $scope.show = function() {
        $scope.var1 = $scope.var1 === false ? true: false;
    };
});

Upon clicking on Span_1 only p tag corresponding to it should show same as for Span_2 and I should achieve that only by one function.

Here is the Plunker: http://plnkr.co/edit/fzgpV68Q7UnHGHmHffZZ?p=preview


Solution

  • Pass variables from html. You can also add cases to make like ng-class or etc and on.

    //Angular code(js)

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
      $scope.variableList = [{state:true},{state:false}];
        $scope.show = function(what,where) {
            switch(what){
              case 'display':
                return $scope.variableList[where].state;
                break;
              case 'click':
                $scope.variableList[where].state = !$scope.variableList[where].state;
                break;
              case 'class':
                return ($scope.variableList[where].state ? 'active' : '');
                break;
            }
        };
    });
    

    Usage(HTML):

    <div ng-app="myApp" ng-controller="myCtrl">
      <div ng-repeat="item in variableList">
        <span ng-class="show('class',$index);" ng-click="show('click',$index)">Span_{{$index+1}}</span>
        <p ng-class="show('class',$index);" ng-show="show('display',$index)">P_{{$index+1}}</p>
      </div>
    </div>