Angular JS - 什么是“$scope”?它与使用 'this' 关键字相比如何?
Angular JS - What is '$scope' and how does it compare to using the 'this' keyword?
我是 Angular JS 的新手,并且以 'this' 的方式学习它:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var app = angular.module('Comment',[]);
app.controller('CommentCtrl',function(){
this.welcome = 'Hello!';
});
</script>
<p ng-app='Comment' ng-controller='CommentCtrl as ctrl'>
Angular says: {{ ctrl.welcome }}
</p>
段落内显示 'Angular says: Hello!'。
然而,我见过的每个 angular 应用程序都使用“$scope”而不是 'this',就像我被教导的那样。
谁能解释一下各自的优缺点,以及我能理解的 $scope 到底是什么?
谢谢。
一些优点:
this
- 调用controller构造函数时,
this
为controller
- 当调用定义在 $scope 对象上的函数时,
this
是 "scope in effect when the function was called"。这可能(也可能不是!)是定义函数的 $scope。因此,在函数内部,this
和 $scope 可能 not 相同。
- $范围
- 每个控制器都有一个关联的 $scope 对象。
- 控制器(构造函数)函数负责设置模型属性并在其关联的 $scope 上 functions/behavior。
- 只有在此 $scope 对象(和父范围对象,如果原型继承正在发挥作用)上定义的方法才能从 HTML/view 访问。例如,来自 ng-click、过滤器等
Here is cool article by Todd Motto
快乐帮助!
我是 Angular JS 的新手,并且以 'this' 的方式学习它:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var app = angular.module('Comment',[]);
app.controller('CommentCtrl',function(){
this.welcome = 'Hello!';
});
</script>
<p ng-app='Comment' ng-controller='CommentCtrl as ctrl'>
Angular says: {{ ctrl.welcome }}
</p>
段落内显示 'Angular says: Hello!'。
然而,我见过的每个 angular 应用程序都使用“$scope”而不是 'this',就像我被教导的那样。
谁能解释一下各自的优缺点,以及我能理解的 $scope 到底是什么?
谢谢。
一些优点:
this
- 调用controller构造函数时,
this
为controller - 当调用定义在 $scope 对象上的函数时,
this
是 "scope in effect when the function was called"。这可能(也可能不是!)是定义函数的 $scope。因此,在函数内部,this
和 $scope 可能 not 相同。
- 调用controller构造函数时,
- $范围
- 每个控制器都有一个关联的 $scope 对象。
- 控制器(构造函数)函数负责设置模型属性并在其关联的 $scope 上 functions/behavior。
- 只有在此 $scope 对象(和父范围对象,如果原型继承正在发挥作用)上定义的方法才能从 HTML/view 访问。例如,来自 ng-click、过滤器等
Here is cool article by Todd Motto
快乐帮助!