和#34;之间的差异"和" $范围"在AngularJS中

时间:2015-03-30 15:08:50

标签: javascript angularjs angularjs-scope angularjs-controller

我阅读了AngularJS文档以及此问题this vs $scope in AngularJS controllers。我在此处获得了所需答案的一部分Difference between this and scope in the controller。我对代码中的“this”和“$ scope”有一个简单的混淆,我跟着CodeSchool Tutorial suggested by Official AngularJS Page,我写了这段代码

控制器(我在Code School练习时使用'this'):

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>

它没有评估AgularJS表达式而没有输出name的值。

但是如果我在我的控制器中使用$ Scope,比如

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

输出正确,即AgularJS表达式{{name}}被评估为控制器中给出的名称值。

任何人都可以向我解释为什么一切都在Code School教程中完美地运行只有'this'?

0 个答案:

没有答案