Pages

Friday, September 30, 2016

Angular Js- Using minified version of Controller,filter js files

Using minifed version of controller JS Files

Here we will use a controller as an example same can be used for Filters

One important thing to note when we isolate controller from our HTML file is during its minification.
The minification also minifies variable in controller and $scope,$http,$filter may become variables a,b,c which are not recognized by angular see the minified version of above controller.js is as follows

controller.js

 angular.module('myApp',[]).controller('myCtrl',function($scope){  
 $scope.names=[  
 {name:'Gaurav',country:'India'},  
 {name:'Mike',country:'USA'},  
 {name:'Steve',country:'Denmark'}  
 ];  
 });  

controller.min.js

 angular.module("myApp",[]).controller("myCtrl",function(n){n.names=[{name:"Gaurav",country:"India"},{name:"Mike",country:"USA"},{name:"Steve",country:"Denmark"}]});  

Here $scope becomes n and this will not be recognized by angular js.To over come this problem use code controller code in controller.js as

controller.js

 angular.module('myApp',[]).controller('myCtrl',["$scope",myCtrl]);  
 function myCtrl($scope){  
 $scope.names=[  
 {name:'Gaurav',country:'India'},  
 {name:'Mike',country:'USA'},  
 {name:'Steve',country:'Denmark'}  
 ];  
 };  

In this we isolate the Controller function but we also tell the module that the first parameter of this function will be "$scope"

The Minified version of this file is

controller.min.js

 function myCtrl(n){n.names=[{name:"Gaurav",country:"India"},{name:"Mike",country:"USA"},{name:"Steve",country:"Denmark"}]}angular.module("myApp",[]).controller("myCtrl",["$scope",myCtrl]);  

Above file also changes the parameter $scope of the function to "n" but when final call is made to function the first parameter is sent as $scope

No comments:

Post a Comment