search

Home  >  Q&A  >  body text

angular.js - Angular中关于控制器编写方式的问题

我是Angular初学者,在学习中有个关于定义控制器的写法问题。

在刚接触的时候,书上是这样写控制的:

var myApp = angular.module('MyApp', []);
myApp.controller('MyController', function($scope){
  // todo...
})

后来在一些网络上的文章,是这样写的:

var myApp = angular.module('MyApp', []);
myApp.controller('MyController', ['$scope', function($scope){
  // todo...
}]);

那么问题来了,后者加了个[],是个什么意思?这两种写法有什么不同呢?

在练习中发现同样的实现用这两种都可以。

阿神阿神2744 days ago475

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-05-15 17:04:43

    The second way of writing is called inline-annotation, see the document dependency injection

    The main purpose of this writing method is to avoid the problem of dependency injection failure due to variable names being replaced during source code compression (uglify).

    If you are interested in the implementation, you can look at handwritten dependency injection

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-15 17:04:43

    is the dependency to be injected. This way of writing is conducive to future code compression

    reply
    0
  • Cancelreply