简体   繁体   中英

how to dynamically add $scope in Angular

here is my HTML:

...
<table class="tickerTable">
<thead>
  <th>Symbol</th>
  <th>Accts</th>
</thead>
<tbody ng-repeat="ticker in tickers">
  <tr ng-click="showTrades(ticker)">
<td >{{ticker.Ticker}}</td>
<td>{{ticker.TradeCount}}</td>
  </tr>
  <tr ng-show="currentItem == ticker">
<td colspan="2">{{trades}}</td>
  </tr>
 </tbody>
</table>

here is the controller:

$scope.showTrades = function(ticker){
  $scope.trades = {};
  $scope.currentItem = ticker;
  $scope.trades = "this is the result of a rest call using the params from $scope.ticker";
};

the table is populated with many rows. for each row i add a blank row that is hidden by default.

when the row is clicked the hidden row displays dynamically generated content that is returned from a rest call made with the params of that particular table row's "ticker" object. the result is injected into $scope.trades and displayed in the now visible TR.

The problem: {{trades}} is being populated in every hidden row along with the revealed row. I only want it to load in the revealed row.

solution

http://plnkr.co/edit/qFZyeuIbt6z5dYEFFHzr?p=preview

In your plnkr you are using ng-if. There is a bug relatead to ng-if in tables #3104 which will cause problems for you. Maybe you can use ng-show instead as you did in the posted HTML?

Next you may add the trades to the containing ticker. So you display the trades belonging to the current ticker. Then only the selected ticker row will have trades.

<!doctype html>
<html ng-app='portfolio'>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"> 
    </script>
    <script src="script.js"></script>
  </head>
  <body>
<table ng-controller = "TickerListCtrl">
    <thead>
      <th>Symbol</th>
    </thead>
    <tbody ng-repeat="ticker in tickers">
      <tr ng-click="showTrades(ticker)">
          <td>{{ticker.Ticker}}</td>
      </tr>
      <tr >
          <td ng-show="currentItem == ticker" colspan="2">{{ticker.trades}}</td>
      </tr>
     </tbody>
</table>
</body>
</html>

$scope.showTrades = function(ticker){
   ticker.trades = "this is trades for ticker: " + ticker.Ticker;
   $scope.currentItem = ticker;   
};

Here is a fork of your plnkr with the described changes.

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