1

I read AngularJS documentation and also this question this vs $scope in AngularJS controllers.I get a part of my required answer here Difference between this and scope in the controller as well. I have a simple confusion regarding "this" and "$scope" in my code, I followed CodeSchool Tutorial suggested by Official AngularJS Page, and I wrote this code

Controller (Using 'this' as I practiced on Code School ):

var myApp = angular.module('myapp', []);
myApp.controller('TestController', function () {
    this.name = 'Yawar Khan';
});

HTML:

<body ng-app="myapp">

  <div ng-controller="TestController">
      <h1> Hello {{name}} to AngularJS ! </h1> 
  </div>

</body>

And it is not evaluating the AgularJS expression and not outputting the value of name.

But if I use $Scope in my controller like

var myApp = angular.module('myapp', []);
myApp.controller('TestController', ['$scope', function ($scope) {
    $scope.name = 'Yawar Khan';
}]);

Output is correct i.e. AgularJS expression {{name}} is evaluated as name value given in controller.

can anyone explain it to me that why everything worked perfectly on Code School tutorials with only 'this' ?

Community
  • 1
  • 1
Abdul Rehman Yawar Khan
  • 1,088
  • 3
  • 17
  • 40
  • 2
    http://stackoverflow.com/questions/22806681/difference-between-this-and-scope-in-the-controller try to have a look here! – d_z90 Mar 30 '15 at 15:11
  • Okay thanks, But can anyone explain it to me that why everything worked perfectly on Code School tutorials with only 'this' ? – Abdul Rehman Yawar Khan Mar 30 '15 at 15:24
  • 1
    We would have to actually see the tutorial to tell you that. It's likely using the controllerAs syntax (which is mentioned and demonstrated in the duplicate question) – Kevin B Mar 30 '15 at 15:26
  • @kevin Thanks, I got the point. http://stackoverflow.com/a/22807947/2860391 Is the answer to my main question – Abdul Rehman Yawar Khan Mar 30 '15 at 15:38

0 Answers0