22

我有以下代码;

var app =
    angular.
        module("myApp",[]).
        config(function($routeProvider, $locationProvider) {
            $routeProvider.when('/someplace', {
                templateUrl: 'sometemplate.html',
                controller: SomeControl
             });
             // configure html5 to get links working on jsfiddle
             $locationProvider.html5Mode(true);
        });

app.controller('SomeControl', ...);

我收到以下错误

Uncaught ReferenceError: SomeControl is not defined from myApp

问题只是我不能使用 app.controller('SomeControl', ...) 语法吗?使用 $routeProvider 时?是唯一有效的语法:

function SomeControl(...)
4

3 回答 3

44

使用引号:

            controller: 'SomeControl'
于 2013-07-03T17:56:54.857 回答
8

就像 Foo L 说的,你需要在SomeControl. 如果不使用引号,则指的SomeControl是未定义的变量,因为您没有使用命名函数来表示控制器。

当您使用您提到的替代方法时function SomeControl(...),您定义了该命名函数。myApp否则,Angular 需要知道它需要在模块中查找控制器。

使用app.controller('SomeControl', ...)语法更好,因为它不会污染全局命名空间。

于 2013-07-03T18:13:38.853 回答
1

上面的答案是正确的,但是,这个错误也可能发生:

  1. 如果您的 html 或 jsp 等页面中的控制器名称与实际的 cotnroller 不匹配

<div ng-controller="yourControllerName as vm">

  1. 此外,如果功能控制器的名称与控制器定义不匹配,则也会发生此错误。

angular.module('smart.admin.vip') .controller('yourController', yourController); function yourController($scope, gridSelections, gridCreationService, adminVipService) { var vm = this; activate();

于 2015-09-03T22:53:44.440 回答