Angular 未将全局函数识别为控制器
Angular is not recognizing global functions as controllers
使用Angular1.3.x,全局函数不被识别为控制器。出了什么问题?我该如何纠正?
function MyController() {
// etc
}
<div ng-controller="MyController"></div>
控制台显示以下错误:
Error: [ng:areq]
http://errors.angularjs.org/1.3.2/ng/areq?p0=MyController&p1=not%20a%20function%2C%20got%20undefined
首先尝试启动您的模块。
在你 HTML 添加 :
ng-app='myApp'
在你的脚本中添加:
var app = angular.module('myApp', []);
根据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).
此更改已在 Angular 1.3.0-beta.15 (changelog) 中完成。
这是 Angular 与旧版本相比的行为变化,旧版本默认将全局函数识别为控制器。这是不好的做法,无论如何都不应该使用。具有讽刺意味的是,为了使用它们,您无论如何都必须为您的应用程序使用适当的设置,并且无论如何都不想在那个时候使用它们。
所以,您需要这样设置您的应用程序:ng-app="myApp
和 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"
将使用全局函数,例如:
function SomeFunction($scope) { //etc
但不要这样做。 :)
使用Angular1.3.x,全局函数不被识别为控制器。出了什么问题?我该如何纠正?
function MyController() {
// etc
}
<div ng-controller="MyController"></div>
控制台显示以下错误:
Error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=MyController&p1=not%20a%20function%2C%20got%20undefined
首先尝试启动您的模块。
在你 HTML 添加 :
ng-app='myApp'
在你的脚本中添加: var app = angular.module('myApp', []);
根据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).
此更改已在 Angular 1.3.0-beta.15 (changelog) 中完成。
这是 Angular 与旧版本相比的行为变化,旧版本默认将全局函数识别为控制器。这是不好的做法,无论如何都不应该使用。具有讽刺意味的是,为了使用它们,您无论如何都必须为您的应用程序使用适当的设置,并且无论如何都不想在那个时候使用它们。
所以,您需要这样设置您的应用程序:ng-app="myApp
和 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"
将使用全局函数,例如:
function SomeFunction($scope) { //etc
但不要这样做。 :)