Part 34 AngularJS controller as vs scope

There are 2 ways to expose the members from the controller to the view - $scope and CONTROLLER AS. The obvious question that comes to our mind at this point is - Why do we have 2 ways of doing the same thing. Which one to use over the other and what are the differences. 

Here are the differences
1. CONTROLLER AS syntax is new and is officially released in 1.2.0. $scope is the old technique and is available since the initial version of angular is released.

2. You can use either one of thes techniques. Both have their own uses. For example, CONTROLLER AS syntax makes your code more readable when working with nested scopes. We discussed this in our previous video.

3. If you want to use $scope it has to be injected into controller function, where as with CONTROLLER AS syntax there is no need for such injection, unless you need it for something else.

Which one to use depends on your personal preference. Some prefer using $scope while others prefer using CONTROLLER AS syntax. One important thing to keep in mind is that, though you are using CONTROLLER AS syntax, behind the scenes angular is still using $scope. Angular takes the controller instance and adds it as a reference on the scope. 

<div ng-controller="cityController as cityCtrl">
    {{cityCtrl.name}}
</div>


In the above example since we are using CONTROLLER AS syntax, angular takes cityCtrl which is the instance of cityController and adds it as a reference on the scope. So in the binding expression, you can read it as $scope.cityCtrl.name 

转载于:https://www.cnblogs.com/gester/p/6535331.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值