angular.js - The standard for dependency injection in angularJS
大家讲道理
大家讲道理 2017-05-15 17:00:16
0
3
689

When I use major communities to check knowledge about Angular, I often see two modes of dependency injection, some of which are controller.('Ctr',[$scope,function($scope){...}] );
Some are directly controller.('Ctr',function($scope){...});
I would like to ask if this latter mode is new and universal?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(3)
滿天的星座

The best practice is to use: controller.('Ctr',['$scope',function($scope){...}]).

  1. As @Deboy said, for js compression.

  2. Better performance. (controller.('Ctr',function($scope){...}), angularjs will parse the parameters of this function, and finally get the content to be injected, while the array-style writing method can skip the parsing step, and the performance will be better). Attached is the source code for reference:

function annotate(fn, strictDi, name) {
  var $inject,
      fnText,
      argDecl,
      last;

  if (typeof fn === 'function') {
    if (!($inject = fn.$inject)) {
      $inject = [];
      if (fn.length) {
        if (strictDi) {
          if (!isString(name) || !name) {
            name = fn.name || anonFn(fn);
          }
          throw $injectorMinErr('strictdi',
            '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
        }
        fnText = fn.toString().replace(STRIP_COMMENTS, '');
        argDecl = fnText.match(FN_ARGS);
        forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
          arg.replace(FN_ARG, function(all, underscore, name) {
            $inject.push(name);
          });
        });
      }
      fn.$inject = $inject;
    }
  } else if (isArray(fn)) {
    last = fn.length - 1;
    assertArgFn(fn[last], 'fn');
    $inject = fn.slice(0, last);
  } else {
    assertArgFn(fn, 'fn', true);
  }
  return $inject;
}
Peter_Zhu

Because in the process of front-end optimization, files such as js will be compressed and some strings will be replaced with single letters. If this is the case, angular injection will fail. The latter one is not processed to prevent injection after compression. The previous one did this, so even if it is compressed, it will not cause the injection to fail

The effects of the two executions during the development phase are the same

曾经蜡笔没有小新

angular的依赖注入的实现方式,没有什么规范/标准可谈,但却是不错的思路。
我之前写过一篇教程,教你手写一个类似angular’s dependency injection system, I hope it will be useful to you: BDD handwritten dependency injection

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template