使用通过angular.module().controller()创建的AngularJS控制器 [英] Using AngularJS Controllers created with angular.module().controller()
问题描述
我对AngularJS还是很陌生,并且正在设置我的第一个应用程序.我希望能够执行以下操作:
I am still very new to AngularJS and am working through setting up my first application. I would like to be able to do the following:
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});
}]);
使用此设置会产生以下错误:
Using this setup the following error is generated:
Uncaught ReferenceError: home is not defined from App
我的问题是:如何使用angular.module.controller()
(或直接$controllerProvider.register()
)注册控制器,以及如何在应用程序的其他位置使用注册的控制器.
My question is: How can I register controllers using angular.module.controller()
(or $controllerProvider.register()
directly) and use the registered controller elsewhere in my app.
我的动机:我想避免使用全局构造函数作为控制器(就像angularjs.org上的大多数示例一样使用)或复杂的命名空间.如果我可以将控制器注册并用作单个变量名(然后不放在全局范围内),那将是理想的选择.
My motivation: I would like to avoid using either global constructor functions as my controllers (as most of the examples on angularjs.org use) or complex namespacing. If I can register and use controllers as single variable names (that are not then put in the global scope) that would be ideal.
推荐答案
尝试使用字符串标识符.
Try using a string identifier.
routeProvider.when('/', {templateUrl: 'partials/home.html', controller: 'home'});
使用文字时,它会寻找一个名为home
的变量,但在这种情况下不存在.
When you use a literal, it is looking for a variable called home
, but that doesn't exist in this case.
这篇关于使用通过angular.module().controller()创建的AngularJS控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!