user1147171
user1147171

Reputation: 1243

"this" vs. $scope in angular

I know similar questions have been asked, and I have read the answers, but I still don't get this, so any help will be appreciated.

The code below works. However, if I use $scope instead of this before the bindTest and clickTest functions (lines 3 and 6), it does not work. Can anyone tell me why? From what I've read, I would have expected $scope to work here.

On the other hand, if I use this instead of $scope before offOrOn (line 8), that does not work.

angular.module('myTestApp', [])
        .controller('MyTestController', function($scope) {
          this.bindTest = function() {
            console.log("bindTest");
          }; 
          this.clickTest = function() {
            console.log("clickTest");
            $scope.offOrOn = 'on';
          };       
        });
button {
 height:25px;
 width:25px; 
}
.on {
 background-color:red;
}
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myTestApp" ng-controller="MyTestController as tester">
 <p ng-bind="tester.bindTest()"></p>
 <button ng-class="offOrOn" ng-click="tester.clickTest()"></button>
</div>
</body>

Also, as an aside, I tried to create a fiddle, but it doesn't work, and the Chrome dev console tells me it won't load the module. I'm curious what's wrong there. But it's great that stackoverflow now provides an identical function that does work!

Upvotes: 1

Views: 96

Answers (1)

a better oliver
a better oliver

Reputation: 26828

You use the controller as syntax. That means that everything added to this is accessible using tester. and everything added to $scope can be used (only) without test..

Now it should be clear why this.offOrOn doesn't work: In your HTML you don't use tester.offOrOn.

Upvotes: 1

Related Questions