Angular 无法将全局函数识别为控制器 [英] Angular is not recognizing global functions as controllers

查看:17
本文介绍了Angular 无法将全局函数识别为控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Angular 1.3.x,全局函数不被识别为控制器.怎么了?我该如何纠正?

Using Angular 1.3.x, global functions are not recognized as controllers. What's going wrong? How do I correct this?

function MyController() {
  // etc
}

<div ng-controller="MyController"></div>

控制台显示以下错误:

错误:[ng:areq]http:///errors.angularjs.org/1.3.2/ng/areq?p0=MyController&p1=not%20a%20function%2C%20got%20undefined

Error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=MyController&p1=not%20a%20function%2C%20got%20undefined

推荐答案

根据 文档:

如果当前 $controllerProvider 被配置为使用全局变量(通过$controllerProvider.allowGlobals()),这也可能是一个全局可访问构造函数(不推荐).

If the current $controllerProvider is configured to use globals (via $controllerProvider.allowGlobals()), this may also be the name of a globally accessible constructor function (not recommended).

此更改来自 Angular1.3.0-beta.15(变更日志).

This change arrived in Angular 1.3.0-beta.15 (changelog).

这是 Angular 对旧版本行为的更改,默认情况下会将全局函数识别为控制器.这是不好的做法,无论如何都不应该使用.具有讽刺意味的是,为了使用它们,您无论如何都必须为您的应用程序使用正确的设置,并且无论如何都不想使用它们.

This is a change in Angular's behavior from older versions, which would recognize global functions as controllers by default. It's bad practice and shouldn't be used anyway. The ironic thing is that in order to use them, you would have to use a proper setup for your app anyway, and wouldn't want to use them at that point anyway.

因此,您需要以这种方式设置您的应用:ng-app="myAppng-controller="MyController"

So, you need to setup your app this way: ng-app="myApp and ng-controller="MyController"

angular.module('myApp', [])
.controller('MyController', function($scope) {
    $scope.author = {
      'name' : 'Mohammad Mohabati',
      'title' : 'Web Design',
      'company' : 'MohabatiPro'
    };
  })
;

allowGlobals 然后可以设置为:

.config(function($controllerProvider) {
  $controllerProvider.allowGlobals();
});

以便 ng-controller="SomeFunction" 将与全局函数一起工作,例如:

so that ng-controller="SomeFunction" will work with a global function like:

function SomeFunction($scope) { //etc

但不要这样做.:)

这篇关于Angular 无法将全局函数识别为控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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