我刚刚开始尝试Angular的最后一天。我正在尝试使用引导选项卡功能。我想根据用户单击的选项卡,将“活动”类动态添加到活动li。以下是我的HTML代码段。
<div ng-controller="TabController as tabs">
{{currentTab}}
<ul class="nav nav-pills" >
<li ng-class="{'active':tabs.isTab('Events')}" ><a href="#" ng-click="setTab('Events')">Events</a></li>
<li ng-class="{'active':tabs.isTab('Surveys')}" ><a href="#" ng-click="setTab('Surveys')">Surveys</a></li>
<li ng-class="{'active':tabs.isTab('Forums')}" ><a href="#" ng-click="setTab('Forums')">Forums</a></li>
</ul>
我正在做的是,当用户单击任何链接时,我正在使用选项卡名称对setTab()方法进行校准,并更改'currentTab'的值。如您所见,我正在将'currentTab'的值打印在页面顶部,并且第一次打印为“事件”。当用户单击不同的选项卡时,我可以更改currentTab的值(页面上打印的值正在更改)。但是唯一的是,“活动”类不会添加到所选选项卡中。对于每个li,我通过调用isTab()方法来检查currentTab值是否与特定选项卡匹配。我在isTab()方法中放了一些日志,但是没有日志被打印出来。
以下是我的模块和控制器定义。
var app = angular.module('myApp',[]);
app.controller('TabController',['$ scope','$ http',function($ scope,$ http){
$scope.currentTab = 'Events';
$scope.setTab = function(tabName) {
console.log('in setTab '+tabName); // this is getting called
$scope.currentTab = tabName;
};
$scope.isTab = function(tabName) {
console.log('in isTab '+tabName); // this is never printed!
return $scope.currentTab === tabName;
//return true;
};
}]);
最佳答案
这是因为controller as
语法。如果使用此模型,则应在this
中定义所有视图模型数据,包括功能子。
this.isTab = function(tabName) {
console.log('in isTab '+tabName);
return this.currentTab === tabName;
};
会的。