Angular -JS. How to make controllers work inside ng-repeat with ng-show

I am very new to Angular and I am trying to do something, if you click on a tab, ng-repeat will show everything with a certain property, and if you click on another tab, ng-repeat witll will show everything with a different property. However, I can't seem to get the tab controller to work alongside 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 the 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 doesn't show anything as isTab () is always false. Can anyone explain to me why?

+3


source to share


1 answer


Use the template I mentioned in the comments to keep a reference to the controller object. This is how you can 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);
    };
})

      

+1


source







All Articles