如何在AngularJS中使用MVC

How to work on MVC in AngularJS

本文关键字:MVC AngularJS      更新时间:2023-09-26

当我试图运行下面的代码时,我得到了这个错误参数'MyController' is not a function, got undefined

<!DOCTYPE html>
<html lang="en" ng-app>
<head>
  <meta charset="utf-8" />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <title>Hello world from Prateek</title>
</head>
<body>
  <div ng-controller="MyController">
    <h1>{{author.name}}</h1>
    <p>{{author.title + ', ' + author.company}}</p>
  </div>
  <script>
    function MyController($scope) {
      $scope.author = {
        'name': 'J Doe',
        'title': 'Designer',
        'company': 'ABC XYZ'
      }
    }
  </script>
</body>
</html>

我想获得要显示的名称,标题和公司,而不是我得到的输出如下

{{author.name}} {{author.title + ', ' + author.company}}

你还没有在javascript中定义任何angular应用。你可以使用创建的模块来定义你的控制器。然后你就可以从视图中访问你的控制器了。下面是一个例子:

<!DOCTYPE html>
<html lang="en" ng-app ="myApp">
<head>
  <meta charset="utf-8" />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <title>Hello world from Prateek</title>
</head>
<body>
  <div ng-controller="MyController">
    <h1>{{author.name}}</h1>
    <p>{{author.title + ', ' + author.company}}</p>
  </div>
  <script>
    var myApp = angular.module("myApp", []); // definition of a module, you use myApp in ng-app directive in the html part so that angularJS initialize itself.
    myApp.controller("MyController", function ($scope) {
      $scope.author = {
        'name': 'J Doe',
        'title': 'Designer',
        'company': 'ABC XYZ'
      }
    });
  </script>
</body>
</html>

你应该先创建模块,然后创建控制器,像

var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
    $scope.author = {
        'name': 'J Doe',
        'title': 'Designer',
        'company': 'ABC XYZ'
      }
});
在你的html中,你应该使用ng-app="module-name",如:
<html lang="en" ng-app="myApp">