Why do we need $scope while ‘this’ just simply work?

Update: It turns out that ‘as’ syntax is the new style since v1.1.5, and it suppose take over all the old style $scope syntax. The nice outcome is that you will never leave a field name or method name in view without any scope prefix which is caused by $scope syntax. Way to go, ‘as’ as ‘this’! It also indicates that AngularJS changes so fast and so many training materials quickly become obsolete even they are old half year old.

Learning AngularJS, still can’t feel the need of using $scope.

The training video on codeschool doesn’t cover $scope concept, just simple use this.

When I came into the code example in controller section on guide, I rewrite the $scope style example using this style, it still works:


(function(angular) {
  'use strict';
var myApp = angular.module('spicyApp1', []);

myApp.controller('SpicyController', ['$scope', function($scope) {
    $scope.spice = 'very';

    $scope.chiliSpicy = function() {
        $scope.spice = 'chili';
    };

    $scope.jalapenoSpicy = function() {
        $scope.spice = 'jalapeño';
    };
}]);


myApp.controller('Spicy2Controller',   function() {
    this.spice = 'very';

    this.chiliSpicy = function() {
        this.spice = 'chili';
    };

    this.jalapenoSpicy = function() {
        this.spice = 'jalapeño';
    };
});

})(window.angular);

<div ng-controller="SpicyController">
 <button ng-click="chiliSpicy()">Chili</button>
 <button ng-click="jalapenoSpicy()">Jalapeño</button>
 <p>The food is {{spice}} spicy!</p>
</div>

<div ng-controller="Spicy2Controller as spicy2">
 <button ng-click="spicy2.chiliSpicy()">Chili</button>
 <button ng-click="spicy2.jalapenoSpicy()">Jalapeño</button>
 <p>The food is {{spicy2.spice}} spicy!</p>
</div>

I remember a post on stackoverfow talking about the difference of $scope and this, something about page loading, basically function defined on $scope won’t trigger on page load, so far I haven’t got any story to support this yet.

Will revisit this post after I understand more.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s