1

i just saw this in the angular.js tutorial on the level 2:

(function() {
  var app = angular.module('gemStore', []);

  app.controller('StoreController', function(){
    this.products = gems;
  });

  app.controller("TabController", function(){
    this.tab = 1;

    this.setTab = function(selectedTab){
      this.tab = selectedTab;
    };
  });

  var gems = [// a lot of code here...]
})();

my doubt is: how does the setTab function alter the value of the TabControler's tab variable? if I use 'this.tab' in the setTab function, the setTab function will be just assigning a variable to it's own internal scope, doesn't it?

2 Answers2

1

You have to look at how angular calls the function internally - it uses something like

app.controller("TabController").setTab.apply($scope, [selectedTab])

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

Which calls your setTab function, but sets the value of this to the $scope object.

It's a little more complicated than that, but that is the "how".

In general, I prefer to use the $scope object in my controllers, as it is and feels a little less "magic".

app.controller("TabController", function($scope){
    $scope.tab = 1;

    $scope.setTab = function(selectedTab){
        $scope.tab = selectedTab;
    };
});

For some more information, this question explains it pretty well: 'this' vs $scope in AngularJS controllers

To see how fn.apply works, here is a simple example:

x = function() { alert(this.test); } 
x(); //alerts "undefined"
x.apply({test: 'hello!'}); //alerts "hello!"
Community
  • 1
  • 1
dave
  • 62,300
  • 5
  • 72
  • 93
1

if I use 'this.tab' in the setTab function, the setTab function will be just assigning a variable to it's own internal scope, doesn't it?

Actually, no.

this, inside your setTab function is a reference some particular instance of the TabController. So, this.tab, means "the tab property of the TabController instance". This instance will be created by Angular internals to handle the view, so you just don't worry about this part.

Edit:

You can use this an example:

var MyConstructor = function() { 
    this.tab = 0;
    this.setTab = function(newTab) {
        this.tab = newTab;
    }; 
    this.logTab = function() {
        console.log(this.tab);
    };
};

var myObj = new MyConstructor();
myObj.logTab(); // prints 0
myObj.setTab(2);
myObj.logTab(); // prints 2

But, as dave mentioned, I would stick with the $scope approach.

Rafael Eyng
  • 4,720
  • 2
  • 33
  • 34
  • It is confusing. It's like I need to force myself to forget some javascript fundamentals in order to use angular.js –  Oct 15 '14 at 16:59
  • @andre, this is a JavaScript fundamental, is not a Angular thing. – Rafael Eyng Oct 15 '14 at 17:03