我正在使用 Angular.js 创建一个应用程序,但我的index.html 文件似乎无法访问我的controller.js 文件。浏览器打印出大括号中的变量,如下所示:{{friend.name}},{{friend.number}}
这是我的 html 文件:
<!DOCTYPE HTML>
<html ng-app>
<head>
<title>Angular Directives</title>
</head>
<body>
<div class="container" ng-controller="demoController">
<h1>Angular Directives</h1>
<h2>ng-model example: two-way binding and $scope</h2>
<h3>Name</h3>
<input type="text" ng-model="name">
<br />
Hello, {{name}}!
<h2>ng-repeat example</h2>
<ul>
<li ng-repeat="friend in friends">{{friend.name}}, {{friend.number}}</li>
</ul>
</div>
</body>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src = "controller.js"></script>
</html>
这是我的controller.js 文件:
var demoController = function($scope) {
$scope.name = "John Doe";
var friend1 = {
name: "Tim Thompson",
number: "111-111-1111"
};
var friend2 = {
name: "Sally Smith",
number: "222-222-2222"
};
var friend3 = {
name: "Billy Bob",
number: "333-333-3333"
};
var friends = [friend1, friend2, friend3];
$scope.friends = friends;
}
最佳答案
您需要将其作为模块包含并在代码中指定该模块。所以像这样。
angular.module("exampleApp", [])
.controller("demoController", function($scope) {
$scope.name = "John Doe";
var friend1 = {
name: "Tim Thompson",
number: "111-111-1111"
};
var friend2 = {
name: "Sally Smith",
number: "222-222-2222"
};
var friend3 = {
name: "Billy Bob",
number: "333-333-3333"
};
var friends = [friend1, friend2, friend3];
$scope.friends = friends;
});
然后设置ng-app="exampleApp"
,您的代码应该可以工作。
编辑:我刚刚意识到我最初的解释可能不清楚。我的意思是 Angular 有一个模块系统。模块是您连接 Controller 的地方。因此,当您添加 ng-app="exampleApp"
时,Angular 会查看它并发现您想要从 exampleApp
模块中提取 Controller 。因此,您需要指定这是您想要在代码中使用的模块,并将 demoController
Controller 附加到该特定模块。
关于javascript - 如何访问 Angular.js 中的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31360826/