w还是相反。
用`scope`,可以轻易声明一个可以到处使用的变量,例如:
app.controller('MainCtrl', function ($scope) {
$scope.title = 'Some title';
});
而使用this,则可以声明一个在controller作用域内使用的变量,类似java的类当中public的局部变量
近来感觉东西越积越多,有些以前用过的小知识到现在都想不起来了,所以决定偶尔做个小笔记,虽然索性就放博客上了。
从若干的基础教程来看,`scope`是angular controller里数据绑定的关键,不管是从controller到view还是相反。
用`scope`,可以轻易声明一个可以到处使用的变量,例如:
app.controller('MainCtrl', function ($sc
近来感觉东西越积越多,有些以前用过的小知识到现在都想不起来了,所以决定偶尔做个小笔记,虽然索性就放博客上了。
从若干的基础教程来看,`scope`是angular controller里数据绑定的关键,不管是从controller到view还是相反。
用`scope`,可以轻易声明一个可以到处使用的变量,例如:
app.controller('MainCtrl', function ($sc
AngularJS:$scope和this
Max
近来感觉东西越积越多,有些以前用过的小知识到现在都想不起来了,所以决定偶尔做个小笔记,虽然索性就放博客上了。
从若干的基础教程来看,scope
是angular controller里数据绑定的关键,不管是从controller到view还是相反。
用scope
,可以轻易声明一个可以到处使用的变量,例如:
app.controller('MainCtrl', function ($scope) { $scope.title = 'Some title'; });
而使用this,则可以声明一个在controller作用域内使用的变量,类似java的类当中public的局部变量。
app.controller('MainCtrl', function () { this.title = 'Some title'; });
从“对象”的角度来看,scope
的写法像是声明了一个全局变量(就是怎么用怎么错的全局变量),然后不停的赋值、修改元素、删除元素。
this配合Controller As
当有了Controller As这个东西的时候,this
就变的很好用。可以轻易搞清楚各个controller
的层级关系,调用到合适的变量。这一点在嵌套的时候尤其明显。举个栗子
使用this之前:
{{ title }}
Scope title: {{ title }}
Parent title: {{ $parent.title }}
Scope title: {{ title }}
Parent title: {{ $parent.title }}
Parent parent title: {{ $parent.$parent.title }}
使用了this之后:
{{ parent.title }}
Scope title: {{ child.title }}
Parent title: {{ parent.title }}
Scope title: {{ grandson.title }}
Parent title: {{ child.title }}
Parent parent title: {{ parent.title }}
其实如果平时就嵌套两层以内,使用起来差别也不是很大。有一点区别就是,要使用scope
,必须为controller
注入$scope
。而使用Controller As
和this
则不必,直接使用即可。所以在某种程度上,你可以决定何时需要使用scope。
这里有个例子。
end
Comments