当控制器位于模块内时,AngularJs $ scope不确定

我正在尝试使用默认设置的angular度种子模板。 在controllers.js我使用

 angular.module('myApp.controllers', []). controller('MyCtrl1', [function($scope) { $scope.test = 'scope found!'; }]) .controller('MyCtrl2', [function() { }]); 

那里的$scope总是未定义的。 当我将控制器从模块中取出并全局注册时,它工作正常。 如下所示:

 function MyCtrl1($scope) { $scope.test = "scope found!"; } MyCtrl1.$inject = ['$scope']; 

有人可以向我解释为什么这是?

你不能混这样的东西。 你需要决定两种可能性之一:

 app = angular.module('test', []); // possibility 1 - this is not safe for minification because changing the name // of $scope will break Angular's dependency injection app.controller('MyController1', function($scope) { // ... }); // possibility 2 - safe for minification, uses 'sc' as an alias for $scope app.controller('MyController1', ['$scope', function(sc) { // ... }]); 

我不会build议使用直接声明Controller的其他语法。 随着你的应用程序的增长,迟早会变得很难保持和跟踪。 但是如果你必须的话,有三种可能性:

 function myController1 = function($scope) { // not safe for minification } function myController2 = ['$scope', function(sc) { // safe for minification, you could even rename scope }] var myController3 = function(sc) { // safe for minification, but might be hard // to read if controller code gets longer } myController3.$inject = ['$scope']; 

这是正确的方法:

 angular.module('myApp.controllers', []); angular.module('myApp.controllers').controller('MyCtrl1', ['$scope', function($scope) { }]); 

我也在寻找那个,看来你需要在函数前键入'$scope' ,如下所示:

  angular.module('myApp.controllers', []). controller('MyCtrl1', ['$scope', function($scope) { $scope.test = 'scope found!'; }]) .controller('MyCtrl2', ['$scope',function() { }]); 

这有点合理,我认为应该更清楚..

当您使用$ scope时,您可以简单地删除'['和']'。

 angular.module('myApp.controllers', []). controller('MyCtrl1', function($scope) { $scope.test = 'scope found!'; }) .controller('MyCtrl2', [ function() { } ]);