简体   繁体   中英

Angularjs Dynamic scope not working

hi i'm trying to create $scope dynamically and set it true on click to show some details inside ng-repeat but it doesn't seem to work ,Here is the plunk plunk

var app=angular.module('myApp',[]);
 app.controller('myCtrl', function($scope){
 $scope.details=[{
 cid:100,
  foo:'first component'
  },

 {
   cid:101,
 foo:'second component'
  },{
   cid:102,
    foo:'third component'
    }];
 $scope.showGraph=function(serverid){
  console.log(serverid);
   if ($scope[serverid] === undefined) {

     $scope[serverid] = true;
     console.log($scope[serverid]);
    } else {
    $scope[serverid] = true;
     }
      };
   });

thanks for your help.Any other suggestions to achieve this is also welcomed.

Currently you are generating some variable name by dynamically passing serverid parameter to it(single scope variable is taking responsibility of all details collection). And the main issue was how you were trying to retrieve variable value from scope isn't correct syntax( ng-if directive expression trying to concatenate strings).

The simplest way to achieve this would be, have a flag showGraph on each element of details collection. Then on click just toggle showGraph flag

  <ul ng-repeat='detail in details'>
    <li><p>{{detail.foo}} <a href="#" ng-click='detail.showGraph =!detail.showGraph'>show graph</a>
    </p>
    <div ng-if='detail.showGraph'>
      show graph here
    </div>
    </li>
  </ul>

Forked Plunkr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM