参数“MainController”不是一个函数,得到了未定义在AngularJS [英] Argument 'MainController' is not a function, got undefined in AngularJS

查看:151
本文介绍了参数“MainController”不是一个函数,得到了未定义在AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的HTML和JS文件

Here is my HTML and JS File

HTML文件

<!DOCTYPE html>
<html ng-app="">

<head>
  <!--Works with latest Stable Build-->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

  <!--Does not work with Latest Beta-->
  <!--UNCOMMENT ME! <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js"></script>-->


  <script src="script.js"></script>
</head>

<body ng-controller="MainController">
  <h1>Angular Playground</h1>
  {{message}}
  <br />Total Length: {{message.length}}
</body>

</html>

JavaScript文件

JAVASCRIPT FILE

var MainController = function($scope) {
    $scope.message = "Hello, Michael";
};

如果我用的是最新的稳定版本,然后我得到以下结果(这显然是正确的):

If I use the latest stable build, then I get the following result (which is obviously correct):

角游乐场

您好,迈克尔总长度:14

Hello, Michael Total Length: 14

不过,如果我使用测试版18,然后我得到了以下错误:

However, if I use Beta 18, then I get the following error:

错误:[NG:AREQ]参数'MainController不是一个函数,得到了不确定

Error: [ng:areq] Argument 'MainController' is not a function, got undefined

和页面返回以下内容:

角游乐场#2

{{消息}}总长度:{{message.length}}

{{message}} Total Length: {{message.length}}

任何想法,这可能是导致此?

Any idea, what could be causing this?

推荐答案

通过角(> 1.3.0)的最新版本中,你不能声明一个全局的构造函数和NG-控制器使用它。

With the latest versions of Angular (>1.3.0), you can't declare a global constructor function and use it with ng-controller.

一个速战速决是创建一个角模块,并添加MainController作为控制器。

A quick fix would be to create an angular module and add MainController as a controller.

在这里,我裹着MainController在IIFE至prevent功能被添加作为一个全球性:

Here I've wrapped MainController in an IIFE to prevent the function from being added as a global:

(function() {

    angular
        .module("appName", [])
        .controller("MainController", MainController);

    MainController.$inject = ["$scope"];

    function MainController($scope) {
        $scope.message = "Hello, Michael";
    };

})();

在你的HTML,你需要的角度模块的添加名字到NG-应用指令:

In your HTML, you'll need to add the name of the angular module to the ng-app directive:

<!DOCTYPE html>
<html ng-app="appName">

<head>
  <!--Works with latest Stable Build-->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

  <!--Does not work with Latest Beta-->
  <!--UNCOMMENT ME! <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js"></script>-->


  <script src="script.js"></script>
</head>

<body ng-controller="MainController">
  <h1>Angular Playground</h1>
  {{message}}
  <br />Total Length: {{message.length}}
</body>

</html>

这篇关于参数“MainController”不是一个函数,得到了未定义在AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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