Angular is not recognizing global functions as controllers [duplicate]

徘徊边缘 提交于 2019-12-11 10:36:40

问题


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>

The console shows the following error:

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


回答1:


According to the docs:

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).

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

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.

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 could then be set with:

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

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

function SomeFunction($scope) { //etc

but don't do it. :)




回答2:


try initating your module first.
In you HTML add :

ng-app='myApp'

In your script add : var app = angular.module('myApp', []);



来源:https://stackoverflow.com/questions/29190214/angular-is-not-recognizing-global-functions-as-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!