2

当使用控制器方法选择某个选项卡时,我正在尝试使用 AngularJS 显示选项卡编号。它没有像预期的那样。非常感谢您对此提供的帮助。

HTML

<body ng-app="coolApp">
    <section ng-controller="panelSelector as panel">
        <ul class="nav nav-pills">
            <li ng-class="{active:panel.isSet(1)}"><a href ng-click="panel.setTab(1)">Concert Band</a></li>
            <li ng-class="{active:panel.isSet(2)}"><a href ng-click="panel.setTab(2)">Ceremonial Band</a></li>
            <li ng-class="{active:panel.isSet(3)}"><a href ng-click="panel.setTab(3)">191st Jazz Combo</a></li>
            <li ng-class="{active:panel.isSet(4)}"><a href ng-click="panel.setTab(4)">Brass Ensemble</a></li>
            <li ng-class="{active:panel.isSet(5)}"><a href ng-click="panel.setTab(5)">Celtic Fire</a></li>
        </ul>
        <p> the tab number is: {{tab}}</p>
    </section>
</body>

代码

var app = angular.module("coolApp", []);
app.controller("panelSelector", function(){
this.tab = 1; 

this.setTab = function(tabChoice){
    this.tab = tabChoice;
};
this.isSet = function(checkTab){
    return this.tab = checkTab;
};
});
4

2 回答 2

4

var app = angular.module("coolApp", []);
app.controller("panelSelector", function(){
  var panel = this;
  panel.tab = 1; 

  panel.setTab = function(tabChoice){
      panel.tab = tabChoice;
  };
  panel.isSet = function(checkTab){
      return panel.tab == checkTab;
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<body ng-app="coolApp">
<section ng-controller="panelSelector as panel">
            <ul class = "nav nav-pills">
                <li ng-class="{active:panel.isSet(1)}"><a href ng-click = "panel.setTab(1)">Concert Band</a></li>
                <li ng-class="{active:panel.isSet(2)}"><a href ng-click = "panel.setTab(2)">Ceremonial Band</a></li>
                <li ng-class="{active:panel.isSet(3)}"><a href ng-click = "panel.setTab(3)">191st Jazz Combo</a></li>
                <li ng-class="{active:panel.isSet(4)}"><a href ng-click = "panel.setTab(4)">Brass Ensemble</a></li>
                <li ng-class="{active:panel.isSet(5)}"><a href ng-click = "panel.setTab(5)">Celtic Fire</a></li>
            </ul>
            <p> the tab number is: {{panel.tab}}</p>
</section>
</body>

  • 您对panelwith的引用this不正确,
  • 您使用{{tab}}而不是{{panel.tab}}显示选定的选项卡,

  • 你的退货声明应该是return panel.tab == checkTab;.

希望问题得到解决!

于 2015-06-25T21:55:15.403 回答
1

this里面的setTab&isSet函数是不同的,你应该声明一个变量并赋值this

控制器

var app = angular.module("coolApp", []);
app.controller("panelSelector", function(){
  var panel = this;
  panel.tab = 1; 

  panel.setTab = function(tabChoice){
      panel.tab = tabChoice;
  };
  panel.isSet = function(checkTab){
      return panel.tab == checkTab;
  };
});
于 2015-06-25T21:06:25.737 回答