角JS - 控制器未定义 [英] Angular JS - Controller Undefined

查看:126
本文介绍了角JS - 控制器未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手到AngularJS世界。我有这样的例子定义AngularJS页面的控制器。最后我试图打开页面时显示在浏览器中的原始文本。

I am a newbie to the AngularJS World. I have this example to define a controller for AngularJS page. I ended up displaying the raw text in the browser when tried to open the page.

我与下载angular.js(LIB / angular.js)到本地文件系统的尝试。

I am trying with downloading the angular.js (lib/angular.js) to local filesystem.

如下面给出的页面:

<!doctype html>
<html ng-app>
    <head>
        <script src="lib/angular.js"></script>
        <script type="text/javascript">
            function MyController($scope) {
                $scope.clock = new Date();
                var updateClock = function() {
                    $scope.clock = new Date();
                };
                setInterval(function() {
                    $scope.$apply(updateClock);
                }, 1000);
                updateClock();
            };
        </script>
    </head>
    <body>
        <div ng-controller="MyController">
            <h1>Hello {{clock}}!</h1>
        </div>
    </body>
</html>

我最终得到如下结果:

I ended up getting the result as below:

你好{{时钟}}!

在浏览器控制台,我得到的错误日志如下:

In the browser console, I am getting the error log as follows:

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

我是什么失踪?

最好的问候,
钱德拉。

Best Regards, Chandra.

推荐答案

您需要启动角模块,并使用相同的创建一个控制器。

You need to initiate an angular module and create a controller using the same.

例如:

var app = angular.module('myApp', []);

app.controller('MyController', function($scope) {
      $scope.clock = new Date();
      var updateClock = function() {
                $scope.clock = new Date();
      };
      setInterval(function() {
          $scope.$apply(updateClock);
      }, 1000);
      updateClock();
});

然后你需要指定在NG-应用=对myApp

And then you need to specify the app in the html markup with ng-app="myApp"

所以你的HTML是:

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

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
    <script src="app.js"></script>
  </head>

  <body>
    <div ng-controller="MyController">
            <h1>Hello {{clock}}!</h1>
        </div>
  </body>

</html>

工作Plunkr

这篇关于角JS - 控制器未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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