Search code examples
angularjs-scope

how to set a dynamic $scope variable in angularjs?


I am new to angular. I have a function where I need to set the ng-show variable to true or false for multiple divs.

The function would look something like this.

$scope.setDivFlags = function(divname,isShow){      
  if (isShow) 
     {$scope.<divname> = true;} 
  else 
     {$scope.<divname> = false;}
 };

I need the values to be set like this:

$scope.div1 = true;
$scope.div2 = true;

and so on....

How to pass div1,div2...etc.. dynamically.


Solution

  • You can define one variable alone and add multiple ng-show attributes like shown below.

    JSFiddle Demo

    Or you can add all the divs to a common parent and then trigger the ng-show.

    JSFiddle Demo

    With angular you can even write the toggle funtion inside ng-click like so.

    <button ng-click="test = !test">toggle visibility</button>
    

    which is the same as writing.

    HTML:

    <button ng-click="toggle()">toggle visibility</button>
    

    JS:

      $scope.toggle = function(){
        $scope.test = !$scope.test;
      }