angular.js的 三种依赖式注入
1、文件压缩:
YUI-compressor
方式1:java -jar C:\yuicompressor-2.4.8.jar C:\demo08.js > C:\demo08.min.js
方式2:结合webStorm-->file->settings-->tools-->fileWatcher-->点击添加-->YUI Compressor JS --> program-->选择路径的“...”按钮,选中对应的jar文件
2、依赖注入的3种类型:
①推断式(猜测式)
这种注入方式不需要关注参数的先后顺序,ng会推断服务是否存在。不能处理压缩或者混淆后的代码,只能处理原始代码
app.controller('myCtrl',function($scope,$http){});
例一:
1 <!DOCTYPE html> 2 <html ng-app="myApp"> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script src="js/angular.js"></script> 7 </head> 8 <body ng-controller="myCtro"> 9 10 <button ng-click="funcShow()">click me</button> 11 12 <script> 13 var app = angular.module('myApp', ['ng']); 14 15 //自定义服务$show 16 app.factory('$show',function(){ 17 return{ 18 show:function(){ 19 alert('hello 推断式依赖注入') 20 } 21 } 22 }) 23 24 //推断式依赖注入,这里控制器会在$scope中找$show服务,压缩后,$scope,$show会被简化为a,b 25 app.controller('myCtrl', function ($scope,$show) { 26 $scope.funcShow=function(){ 27 $show.show(); 28 } 29 }); 30 31 </script> 32 </body> 33 </html>
②标记式
直接调用$inject属性来完成依赖的标记
var ctrFunc = function ($show,$write,$scope) {
};
//对控制器的回调函数 设置依赖注入时的标记
ctrFunc.$inject = ['$show','$write','$scope'];
app.controller('myCtrl',ctrFunc);
1 <!DOCTYPE html> 2 <html ng-app="myApp"> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script src="js/angular.js"></script> 7 </head> 8 <body ng-controller="myCtro"> 9 10 <button ng-click="funcBtn1()">btn1</button> 11 <button ng-click="funcBtn2()">btn2</button> 12 13 <script> 14 var app = angular.module('myApp', ['ng']); 15 16 //通过factory创建一个服务$show 17 app.factory('$show',function(){ 18 return { 19 show:function(){ 20 alert('Hello $show service'); 21 } 22 } 23 }); 24 25 //通过factory创建一个服务$write 26 app.factory('$write',function(){ 27 return { 28 write:function(){ 29 alert('Hello $Write service'); 30 } 31 } 32 }); 33 34 //参数的顺序 要与 下面的控制器 注入标记的 顺序一致 个数也要一致 35 var ctrFunc=function($show,$write,$scope){ 36 $scope.funcBtn1=function(){ 37 $show.show(); 38 } 39 $scope.funcBtn2=function(){ 40 $write.write(); 41 } 42 }; 43 //对控制器的回调函数 设置依赖注入时的标记 44 ctrFunc.$inject=['$show','$write','$scope']; 45 app.controller('myCtro',ctrFunc); 46 </script> 47 </body> 48 </html>
将原始数据压缩为min.js依然可以处理.
③行内式
允许开发人员 将一个字符型数组 作为对象的参数,在这个数组中,除了最后一个元素必须是函数体之外,都是服务名
app.controller('myCtrl',['$scope','$http',function($scope,$http){}])
1 <!DOCTYPE html> 2 <html ng-app="myApp"> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script src="js/angular.js"></script> 7 </head> 8 <body ng-controller="myCtro"> 9 <script> 10 var app = angular.module('myApp', ['ng']); 11 12 app.factory('$print',function(){ 13 return{ 14 printSth:function(msg){ 15 alert(msg); 16 } 17 } 18 }) 19 20 //采用行内式 依赖注入的方式 注入 $print服务 21 app.controller('myCtro', ['$scope','$print',function ($scope,$print) { 22 $print.printSth('hello 行内式 依赖注入'); 23 }]); 24 </script> 25 </body> 26 </html>
同样可以处理压缩后的min.js