gpt4 book ai didi

当 Controller 位于模块内部时,AngularJs $scope 未定义

转载 作者:行者123 更新时间:2023-12-03 06:35:19 24 4
gpt4 key购买 nike

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

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

}]);

那里的$scope始终是未定义的。当我将 Controller 从模块中取出并全局注册时,它工作正常。就像这里:

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 的语法。随着应用程序的增长,迟早会变得难以维护和跟踪。但如果你必须这样做,有 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'];

关于当 Controller 位于模块内部时,AngularJs $scope 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16284769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com