简体   繁体   English

如何在Angular中动态添加$ scope

[英]how to dynamically add $scope in Angular

here is my HTML: 这是我的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. 单击该行时,隐藏行将显示动态生成的内容,该内容是通过使用该特定表行的“ ticker”对象的参数进行的rest调用返回的。 the result is injected into $scope.trades and displayed in the now visible TR. 结果将被注入$ scope.trades并显示在现在可见的TR中。

The problem: {{trades}} is being populated in every hidden row along with the revealed row. 问题:{{trades}}随显示行一起填充在每个隐藏行中。 I only want it to load in the revealed row. 我只希望它加载到显示的行中。

solution

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

In your plnkr you are using ng-if. 在您的plnkr中,您正在使用ng-if。 There is a bug relatead to ng-if in tables #3104 which will cause problems for you. #3104中有一个与ng-if相关的错误,它将为您带来问题。 Maybe you can use ng-show instead as you did in the posted HTML? 也许可以像在发布的HTML中那样使用ng-show代替?

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. 是带有描述的更改的plnkr的一个分支。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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