angularjs controller 和 controllerAs 的使用

文章参考

http://blog.csdn.net/wp270280522/article/details/45333679

http://blog.csdn.net/xuanwuziyou/article/details/52885321

一、在DOM节点中使用controllerAs

function ParentController(){
    this.name = "Ada";
}

function ChildController(){
    this.name = "Bill";
}

function MiddController($scope){
    $scope.name = "Mill";
}

(1)使用$parent的方式调用

<div ng-controller="ParentController">
	<div ng-controller="ChildController">
		<span>{{name}}</span>
		<br>{{$parent.name}}</br>
	</div>
</div>

 备注:如果控制器的层次比较多,则就需要使用多个$parent,这种方式与HTML控制器的层级耦合的比较紧密

(2)使用controller as 的方式

<div ng-controller="ParentController as pc">
    <div ng-controller="MiddController">
        <div ng-controller="ChildController as cc">
            <span>{{pc.name}}</span>
            <br>{{cc.name}}</br>
        </div>
    </div>
</div>

 备注:即使HTML中的控制器层级比较深,也不会需要明确$parent的个数,只需要了解变量的控制范围,就能够准确招到具体的控制器的属性

二、在指令中使用controllerAs

angular.module('myApp',[])  
.directive('bookList',function(){  
    return {  
        restrict:'ECAM',  
        //此处定义了该指令的controller属性  
        controller:function($scope){  
            $scope.books=[  
                {name:'php'},  
                {name:'javascript'},  
                {name:'java'}  
            ];  
            this.addBook=function(){       //或者 scope.addBook=...  
                alert('test');  
            }  
        },  
        controllerAs:'bookListController', //给当前controller起个名称  
        template:'<ul><li ng-repeat="book in books">{{ book.name }}</li></ul>',  
        replace:true,  
        //link中注入 bookListController ,就可以使用它的方法了  
        link:function(scope,iElement,iAttrs,bookListController){  
            iElement.on('click',bookListController.addBook);  
        }  
    }  
})  
.controller('firstController',['$scope',function($scope){  
}])  

备注:控制器被注入到Link函数中。 

猜你喜欢

转载自hbiao68.iteye.com/blog/2366725