AngularJS 'Controller As'用法

AngularJS 1.2版本中提供了Controller As语法,简单说就是可以在Controller中使用this来替代$scope,使得Controller更像一个传统的JS类,相对于$scope的继承树要理解上要简单一些。

基础用法

传统的Controller是这样写的:

app.controller('MainCtrl', function($scope) {
    $scope.title = 'Some title';
});

这种写法下,$scope是注入到MainCtrl中的服务,是Dom元素和Controller之间的粘合剂。

<div ng-controller="MainCtrl">
    { { title } }
</div>

这个孤单的title常常让初学者疑惑。

在AngularJS 1.2版本之后,我们可以这样写:

app.controller('MainCtrl', function() {
    this.title = 'Some title';
});

这种写法下,MainCtrl更像是一个JS类:

var MainCtrl = function() {
    this.title = 'Some title';
};
var main = new MainCtrl();

在页面上使用时就可以使用Controller As语法,实例化对象

<div ng-controller="MainCtrl as main">
    { { main.title } }
</div>

嵌套块

这种理解上的好处在嵌套块中更加明显:

<div ng-controller="MainCtrl">
    { { title } }
    <div ng-controller="AnotherCtrl">
        { { title } }
        <div ng-controller="YetAnotherCtrl">
            { { title } }
        </div>
    </div>
</div>

这个title可能是$scope继承树上的任意一个。而使用Controller as之后:

<div ng-controller="MainCtrl as main">
    { { main.title } }
    <div ng-controller="AnotherCtrl as another">
        Scope title: { { another.title } }
        Parent title: { { main.title } }
        <div ng-controller="YetAnotherCtrl as yet">
            Scope title: { { yet.title } }
            Parent title: { { another.title } }
            Parent parent title: { { main.title } }
        </div>
    </div>
</div>

这就清晰很多。

Directive用法

在Directive中,我们可以这样使用:

app.directive('myDirective', function() {
    return {
        restrict: 'EA',
        template: '<div>{ { my.title } }</div>',
        controller: function() {
            this.title = 'Some title';
        },
        controllerAs: 'my'
    };
});

$watch

只是$watch还是需要注入$scope:

app.controller('MainCtrl', function($scope) {
    this.title = 'Some title';

    $scope.$watch(angular.bind(this, function() {
        return this.title;
    }), function(newVal, oldVal) {});
});

本文地址:http://corncandy.github.io/2014/06/06/angularjs-controller-as/

转载于:https://www.cnblogs.com/CloudMu/p/3772767.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值