使用通过 angular.module().controller() 创建的 AngularJS 控制器 [英] Using AngularJS Controllers created with angular.module().controller()

查看:22
本文介绍了使用通过 angular.module().controller() 创建的 AngularJS 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆