AngularJS $injector 依赖注入详解

(编辑:jimmy 日期: 2024/10/3 浏览:2)

推断式注入

这种注入方式,需要在保证参数名称与服务名称相同。如果代码要经过压缩等操作,就会导致注入失败。

 app.controller("myCtrl1", function($scope,hello1,hello2){
    $scope.hello = function(){
      hello1.hello();
      hello2.hello();
    }
  });

标记式注入

这种注入方式,需要设置一个依赖数组,数组内是依赖的服务名字,在函数参数中,可以随意设置参数名称,但是必须保证顺序的一致性。

var myCtrl2 = function($scope,hello1,hello2){
    $scope.hello = function(){
      hello1.hello();
      hello2.hello();
    }
  }
  myCtrl2.$injector = ['hello1','hello2'];
  app.controller("myCtrl2", myCtrl2);

内联式注入

这种注入方式直接传入两个参数,一个是名字,另一个是一个数组。这个数组的最后一个参数是真正的方法体,其他的都是依赖的目标,但是要保证与方法体的参数顺序一致(与标记注入一样)。

app.controller("myCtrl3",['$scope','hello1','hello2',function($scope,hello1,hello2){
    $scope.hello = function(){
      hello1.hello();
      hello2.hello();
    }
  }]);

$injector常用的方法

在angular中,可以通过angular.injector()获得注入器。

var $injector = angular.injector();

通过$injector.get('serviceName')获得依赖的服务名字

$injector.get('$scope')

通过$injector.annotate('xxx')获得xxx的所有依赖项

$injector.annotate(xxx)

样例代码

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script src="/UploadFiles/2021-04-02/angular.min.js">

以上就是对AngularJS injector的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!

一句话新闻

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。