我对 AngularJS 还很陌生,正在设置我的第一个应用程序。我希望能够执行以下操作:
angular.module('App.controllers', [])
.controller('home', function () {
$scope.property = true;
}]);
angular.module('App', ['App.controllers'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {templateUrl: 'partials/home.html', controller: home});
}]);
使用此设置会生成以下错误:
Uncaught ReferenceError: home is not defined from App
我的问题是:如何使用angular.module.controller()
(或直接$controllerProvider.register()
)注册 Controller 并在其他地方使用注册的 Controller 在我的应用程序中。
我的动机:我想避免使用全局构造函数作为我的 Controller (正如 angularjs.org 上的大多数示例所使用的那样)或复杂的命名空间。如果我可以注册并使用 Controller 作为单个变量名称(然后不放入全局范围),那就太理想了。
最佳答案
尝试使用字符串标识符。
routeProvider.when('/', {templateUrl: 'partials/home.html', controller: 'home'});
当您使用文字时,它会查找名为 home
的变量,但在本例中该变量不存在。
关于angularjs - 使用通过 angular.module().controller() 创建的 AngularJS Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11211999/