0

我刚买了一本关于 Angular JS 的书。我正在设置第一个项目,这非常简单。只有一个 Angular 元素需要渲染。我想从一开始就正确设置,所以我现在想克服这个简单的问题。为简单起见, angular.js 文件和 app.js 文件位于 index.html 所在的同一文件夹中。我下载了最新版本的 angular (1.3.2),并尝试使用最小化的 .js 文件,然后再尝试使用未压缩的文件。这段代码是从我正在使用的书中复制粘贴的,该书于 2013 年出版。

索引.html:

<html ng-app>
    <head>
        <script src="angular.js"></script>
        <script src="app.js"></script>
    </head>
    <body>
        <div ng-controller='HelloController'>
            <p>{{greeting.text}}, World</p>
        </div>
    </body>
</html>

应用程序.js:

function HelloController($scope) {
    $scope.greeting = { text: 'Hello' };
}

在我的浏览器(最新版本的 Chrome)中打开 index.html 时,“{{greeting.text}}”区域显示为该字符串 {{greeting.text}},而不是变量的值。当我打开开发工具时,我看到控制器上有一个错误,它没有被定义为控制器。我知道这是非常简单的东西,但我想从一开始就拥有我的所有声明,以便我可以学习 Angular。任何帮助,将不胜感激。

4

5 回答 5

3

更新

同意@JaredReeves,所以像这样声明模块变量

//module file 
angular.module('yourAppDep');

// Controller One File
    angular.module('yourAppDep').controller('MyCtrl', function () {
      // ...
});

像这样在 module.js 文件中为您的应用程序创建模块

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

AngularMVCApp.controller('HelloController', HelloController);

像下面这样改变你的html

<html ng-app="AngularMVCApp">

像这样改变你的控制器

function HelloController($scope) {
    $scope.greeting = { text: 'Hello' };
}

// The $inject property of every controller (and pretty much every other type of 
 //object in Angular) needs to be a 
 //string array equal to the controllers arguments, only as strings
 HelloController.$inject = ['$scope'];

您还可以在这里查看基本教程:http: //www.codeproject.com/Articles/806029/Getting-started-with-AngularJS-and-ASP-NET-MVC-Par

于 2014-11-14T13:59:22.520 回答
3

最终,您的原始代码将在 Angular 1.3 之前运行。在 Angular 1.3 中不再支持全局函数控制器。
http://plnkr.co/edit/3BuxfWLXGqtxImsNTzWm?p=preview

<html ng-app>
    <head>
        <script src="1.22_angular.js"></script>
        <script src="app.js"></script>
    </head>
    <body>
        <div ng-controller='HelloController'>
            <p>{{greeting.text}}, World</p>
        </div>
    </body>
</html>
于 2014-11-14T14:38:03.407 回答
0

他们这样表现出来似乎很奇怪。通常您会立即开始使用模块,如下所示:

在 html 中

<html ng-app="app">

在js中

angular.module("app",[])

.controller("HelloController",function ($scope) {
    $scope.greeting = { text: 'Hello' };
});

我不确定你的符号是否也能正常工作,但这是设置 Angular 应用程序的标准方法,我见过的所有教程都使用了这种方法。

于 2014-11-14T14:00:05.737 回答
0

你的控制器错了。看看这里。它一定是这样的

yourApp.controller('HelloController', function ($scope) {
   $scope.greeting = { text: 'Hello' }; 
}
于 2014-11-14T14:01:36.507 回答
0

请尝试以下示例,

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-controller="empController">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
function empController($scope) {
    $scope.firstName = "Tom";
    $scope.lastName = "Jerry";
}
</script>

于 2014-11-14T14:07:50.537 回答