当控制器位于模块中时,AngularJs的$scope未定义



我试图使用默认设置的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'];
谁能给我解释一下这是为什么?

你不能把这些东西混在一起。您需要在以下两种可能性中做出选择:

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的其他语法。随着应用的发展,它迟早会变得难以维护和跟踪。但如果你必须这样做,有三种可能:

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

最新更新