46

我正在尝试使用具有默认设置的 angular-seed 模板。在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'];

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

4

4 回答 4

67

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

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) {
    // ...
}]);

我不建议使用直接声明 Controller 的其他语法。随着您的应用程序的发展,迟早会变得难以维护和跟踪。但如果必须,有 3 种可能性:

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'];
于 2013-04-29T17:42:01.057 回答
17

这是正确的方法:

angular.module('myApp.controllers', []);

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

}]);
于 2013-07-14T21:29:00.437 回答
1

I was also searching for that one, it seems that you need to type '$scope' before the function, as below:

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

  }]);

It kinda makes sense, I think it should be more clear though..

于 2013-07-14T19:42:11.857 回答
-1

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

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

    }
  ]);

于 2015-03-18T12:12:13.403 回答