将元素的id传递给ng-class指令

时间:2014-12-31 18:37:15

标签: angularjs angularjs-directive

我全神贯注但无法找到获取元素id的方法 传递给ng-class函数的ng-class

<ol ng-controller="PanelController as panel">
     <li id="IdIWant" ng-class="{active: panel.isSelected(WHAT GOES HERE?)}"></li>
     <li id="IdIWant2" ng-class="{active: panel.isSelected(WHAT GOES HERE?)}"></li>
     <li id="IdIWant3" ng-class="{active: panel.isSelected(WHAT GOES HERE?)}"></li>
</ol>

和javascript:

app.controller("PanelController", function(){
        this.selectTab = function(setTab){
            this.tab  = setTab;
        };
            this.isSelected = function(checkTab){
                console.log(checkTab);
                return this.tab===checkTab;
            }
        });

长篇故事
在教程中我得到:

<li ng-class="{active: panel.isSelected(1)}">1</li>
<li ng-class="{active: panel.isSelected(2)}">2</li>
<li ng-class="{active: panel.isSelected(3)}">3</li>

然后我可以根据数字设置活动类但我想通过 来自id,ng-data或其他方式的数字(1,2或3)(因此不在panel.isSelected()中写入) 像:

<li id="1" ng-data="1" ng-class="{active: panel.isSelected(WHAT GOES HERE?)}">1</li>

1 个答案:

答案 0 :(得分:1)

我可能会以不同的方式和更有棱角的方式来做。例如,设置面板的视图模型: -

设置面板的控制器:

.controller("PanelController", function() {

      var selectedTab;

      /*Set up the panels*/
      this.panels = [{
        id: 'panel1',
        text: 'Panel1'
      }, {
        id: 'panel2',
        text: 'Panel2'
      }, {
        id: 'panel3',
        text: 'Panel3'
      }];

      /*Set Default tab*/
      selectedTab = this.panels[0];


      this.selectTab = function(tab) {
        selectedTab = tab;
      };

      this.isSelected = function(tab) {
        return angular.equals(selectedTab, tab);
      }
    });

使用ng-repeat查看,虽然这显示了id,但根本不需要它。但是,您可以从视图模型设置id,甚至可以硬编码,并使用ng-repeat的$index属性添加索引ng-attr-idng-class正如您刚才所做的那样,除了实施之外。为简洁起见,添加了一个ng-click。虽然根据你问题中的示例代码不清楚它来自何处(如果你澄清这可以根据需要进行调整)。:

   <li ng-repeat="pnl in panelCtrl.panels track by pnl.id" 
       ng-attr-id="{{pnl.id}}" 
       ng-class="{active: panelCtrl.isSelected(pnl)}" 
       ng-click="panelCtrl.selectTab(pnl)">{{pnl.text}}</li>

示例演示

&#13;
&#13;
angular.module('app', []).controller("PanelController", function() {

  var selectedTab;

  /*Set up the panels*/
  this.panels = [{
    id: 'panel1',
    text: 'Panel1'
  }, {
    id: 'panel2',
    text: 'Panel2'
  }, {
    id: 'panel3',
    text: 'Panel3'
  }];

  /*Default tab*/
  selectedTab = this.panels[0];


  this.selectTab = function(tab) {
    selectedTab = tab;
  };

  this.isSelected = function(tab) {
    return selectedTab === tab;
  }
});
&#13;
.active {
  color: blue;
  font-size: bold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <ol ng-controller="PanelController as panelCtrl">
    <li ng-repeat="pnl in panelCtrl.panels track by pnl.id" ng-attr-id="{{pnl.id}}" ng-class="{active: panelCtrl.isSelected(pnl)}" ng-click="panelCtrl.selectTab(pnl)">{{pnl.text}}</li>
  </ol>
</div>
&#13;
&#13;
&#13;