当前位置:首页> 正文

AngularJs Injecting Services Into Controllers详解

AngularJs Injecting Services Into Controllers详解

本文主要介绍AngularJs Injecting Services Into Controllers的知识,这里整理了一下相关资料,及示例代码,帮助大家学习和理解,有兴趣的小伙伴可以参考下

     把service当作被依赖的资源加载到controller中的方法,与加载到其他服务中的方法很相似。

  由于javascript是一个动态语言,DI不能弄明白应该通过static types(like in static typed languages)注入哪一个service。因此,我们需要通过$inject属性指定service名称, 它是一个包含需要注入的service名称的字符串数组。service ID顺序的重要性:工厂方法中的参数顺序,与service在数组中的顺序一致。工厂方法的参数名称并不重要,但是按照惯常的做法,他们与service ID一一匹配,下面将讨论这样做的好处。

1.显式依赖注入

 function myController($scope,$loc,$log) {   $scope.firstMethod = function() {   //使用$location service  $loc.setHash(); };   $scope.secondMethod = function() { //使用$log service $log.info(‘…')   }; } myController.$inject = [‘$location','$log']; 

例子:

   explicit-inject-service 
  • {{msg}}

 2. 隐式依赖注入

 angular DI的一个新特性,允许通过参数名称决定依赖。让我们重写上面的例子,展示如何隐式注入$window、$scope与notify service。

例子:

   implicit-inject-service 
  • {{msg}}
 

  虽然这样很方便,但是假如我们需要压缩、混淆我们的代码,这可能会导致参数名称被更改,遇到这种情况的时候,我们还是需要使用显式声明依赖的方式。

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

以上就是AngularJs Injecting Services Into Controllers详解的详细内容,更多请关注易知道|edz.cc其它相关文章!

展开全文阅读

相关内容