简体   繁体   English

Angular JS依赖注入-最佳实践

[英]Angular JS Dependency Injection - Best Practice

I recently started working on my first Angular JS project, and I want to make sure I'm handling Multiple dependance injection correctly. 我最近开始从事我的第一个Angular JS项目,我想确保自己正确处理了多依赖注入。 Any suggestions or feed back will be greatly appreciated! 任何建议或反馈将不胜感激!

var app = angular.module('app', [
  'ngRoute',
  'ngIdle',
  'ui.bootstrap'
]);

app.controller('testCtrl', [
  '$scope', '$http', '$timeout', '$location', 'SessionService',
  function($scope, $http, $timeout, $location, SessionService) {

  // Do Stuff
}]);

I imagine you're just wondering about syntax here, There are a few different ways: 我想您在这里只是想知道语法,有几种不同的方法:

MyAppModule.controller("MyCtrl",MyCtrl);
MyCtrl.$inject = ['$scope', '$http', '$timeout', '$location', 'SessionService'];
function MyCtrl($scope, $http, $timeout, $location, SessionService){
    //..do stuff
}

I like this way because it is pretty decoupled, and can be separated easily from angular, wrapped up in a !function(){}() will keep it out of the global space. 我喜欢这种方式,因为它很容易解耦,并且可以很容易地与角度分离,包裹在!function(){}()可以使它脱离全局空间。 This way is also the least work for the injector initialization. 这种方式对于喷射器初始化也是最少的工作。

Then there is the array syntax you have shown. 然后是您显示的数组语法。 That's nice if you like brackets ( }]) ). 如果您喜欢方括号( }])那就很好。

You can also forgo manually writing the string names and use a build tool like ngmin . 您也可以放弃手动编写字符串名称,而使用ngmin之类的构建工具。 Though you'd have to follow the guidelines for declaring your dependencies. 尽管您必须遵循准则来声明依赖项。

I wouldn't say there are any certain best practices associated with any of this, but its more of a preference. 我不会说有任何与此相关的最佳实践,但是它更偏向于优先。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM