3

I am very new at Angular and I am trying to make something where if you click a tab, ng-repeat will show everything with a certain property and if you click a different tab, ng-repeat witll show everything with a different property. However I cant get the tab controller to work along with ng-show. Here is my code:

   <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>

Here is the js code for TabController:

    app.controller('TabController', function(){
       this.tab = 1;
       this.setTab = function(t){
         this.tab = t;
       }
       this.isTab = function(t){
         return (this.tab == t);
       }
    })

However ng-show shows nothing as isTab() is always false. Can anyone explain to me why?

ylin6
  • 63
  • 3
  • Is there any output in the javascript console? – Red Cricket May 30 '15 at 04:58
  • It's a common problem, `this` changes context inside the function (it is not reference to the controller *inside* the function). People use a [pattern](http://stackoverflow.com/q/962033/398606) where they keep a reference to the controller w/`self`. Then you can use `self` inside a function to access the controller. (Trying to find an Angular specific example) – Sunil D. May 30 '15 at 05:20

1 Answers1

1

Use the pattern I referred to in the comments to keep a reference to the controller object. This is how you might do it using the "controller as" syntax in AngularJS:

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);
    };
})
Community
  • 1
  • 1
Sunil D.
  • 17,539
  • 6
  • 48
  • 60
  • I changed it like the way you said but still nothing is showing up. Seems like the tabCtrl only works within the scope of ``` ``` – ylin6 May 31 '15 at 23:16
  • Found the solution, was a scoping problem. Moved ng-controller to parent div and everything worked! – ylin6 Jun 01 '15 at 00:35