The use of angularjs controller and controllerAs

Article reference

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

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

 

1. Using controllerAs in DOM nodes

 

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

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

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

 

(1) Use $parent method to call

 

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

 Note: If there are many levels of controllers, you need to use multiple $parents, which is more tightly coupled with the level of HTML controllers .

 

(2) The way to use 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>

 Remarks: Even if the controller level in HTML is relatively deep, you do not need to specify the number of $parents. You only need to understand the control scope of variables, and you can accurately recruit the attributes of specific controllers .

 

2. Use controllerAs in the instruction

 

angular.module('myApp',[])  
.directive('bookList',function(){  
    return {  
        restrict:'ECAM',  
        //The controller property of the instruction is defined here  
        controller:function($scope){  
            $scope.books=[  
                {name:'php'},  
                {name:'javascript'},  
                {name:'java'}  
            ];  
            this.addBook=function(){       //或者 scope.addBook=...  
                alert('test');  
            }  
        },  
        controllerAs:'bookListController', // Give the current controller a name  
        template:'<ul><li ng-repeat="book in books">{{ book.name }}</li></ul>',  
        replace:true,  
        //Inject bookListController into the link, you can use its methods  
        link:function(scope,iElement,iAttrs,bookListController){  
            iElement.on('click',bookListController.addBook);  
        }  
    }  
})  
.controller('firstController',['$scope',function($scope){  
}])  

Remark: The controller is injected into the Link function. 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326748420&siteId=291194637