我是 Angular 的新手,我正在尝试做一些事情,如果您单击一个选项卡,ng-repeat 将显示具有特定属性的所有内容,如果您单击不同的选项卡,ng-repeat 将显示具有不同属性的所有内容属性(property)。但是我无法让选项卡 Controller 与 ng-show 一起工作。这是我的代码:
<ul class = "nav nav-pills" ng-controller = "TabController as tabCtrl">
<li ng-class="{'active':tabCtrl.isTab(1)}">
<a ng-click="tabCtrl.setTab(1)" href = "#"> All </a>
</li>
<li ng-class="{'active':tabCtrl.isTab(2)}">
<a ng-click="tabCtrl.setTab(2)" href = "#"> Online </a>
</li>
<li ng-class="{'active':tabCtrl.isTab(3)}">
<a ng-click="tabCtrl.setTab(3)" href="#"> Offline </a>
</li>
</ul>
...
<div class = "user" ng-repeat="streamer in twitch.users" ng-show="tabCtrl.isTab(1)">
//... repeated stuff here
</div>
这是 TabController 的 js 代码:
app.controller('TabController', function(){
this.tab = 1;
this.setTab = function(t){
this.tab = t;
}
this.isTab = function(t){
return (this.tab == t);
}
})
但是 ng-show 没有显示任何内容,因为 isTab() 始终为 false。谁能给我解释一下为什么?
最佳答案
使用 pattern我在评论中提到要保留对 Controller 对象的引用。这就是在 AngularJS 中使用“controller as”语法的方法:
app.controller('TabController', function(){
var self = this;
this.tab = 1;
this.setTab = function(t){
// inside a function "this" is not the controller
// it is a reference to the function
self.tab = t;
};
this.isTab = function(t){
return (self.tab == t);
};
})
关于ng-repeat - Angular-JS。如何使用 ng-show 让 Controller 在 ng-repeat 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30542409/