Sunday, 5 July 2015

Order of parameters in controller and custom directive link function in AngularJS

Have you ever tried changing the order of parameters of AngularJS app controller or link function in Angularjs directive?. If you have done so you will find something important difference between the two. Controller callbacks parameters are strict naming convention. Although it does not depends on it's order but directive link function parameters are maintains order of the parameters though it does not maintain naming convention.

 
Suppose say we have this controller defined.

var app = angular.module('app',[]);

app.controller('MyCtrl',function($scope,$http) {

});

Now if you change the order like say
app.controller('MyCtrl',function($http, $scope) {

});

$http and $scope does not change there property. 

But now take one app directive link function say

A.
app.directive('panel',function(scope,element, attrs, ctrl, transclude) {
});

If you change the order like say

B.
app.directive('panel',function(element,scope, ctrl, attrs, transclude) {
});

Then here element meant to be scope, scope meant to be element, ctrl meant to be attrs and attrs 
meant to be ctrl. This means in case of directive link function order of argument is very important.
The order mentioned at below point A. is actually the order and if you change the names it will not change the order. You can even change there name then also it will retain the same order. You can 
write like this 

C.
app.directive('panel,function(a, b, c, d, e) {
});

Here a means scope, b means element, c means attrs, d means ctrl and e means transclude.


But in case of controller callback function name cannot be change so you can change the order.

But you can change the name or order in this case also for that you have to define your controller 
like this.

app.controller('MyCtrl',[$http,$scope, function($http, $scope) {
}]);

You can even change their name or to say put alias like this.

app.controller('MyCtrl',[$http,$scope, function(a, b) {
}]);

Here a means $http and b means $scope.

---------------------------------------------------------------------------------------------------------------------------

#angularjs #javascript #jquery #ajax #controller #directive

No comments: