我在html文件中有以下代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title></title>
<script src="Scripts/angular.min.js"></script>
<link href="Styles.css" rel="stylesheet"
</head>
<body ng-app="FirstModule">
<div ng-controller="myController">
<table>
<thead>
<tr>
<th>Name</th>
<th>Likes</th>
<th>DisLikes</th>
<th>Likes/Dislikes</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="technology in technologies">
<td>{{ technology.name}}</td>
<td>{{ technology.likes}}</td>
<td>{{ technology.dislikes}}</td>
<td>
<input type="button" value="Like" ng-click="incrementLikes(technology)" />
<input type="button" value="Like" ng-click="incrementDisLikes(technology)" />
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
js中的代码是
/// <reference path="angular.min.js" />
var myApp = angular.module("FirstModule", []);
var myController = function ($scope) {
var technologies = [
{ name: "C#", likes: 0, dislikes: 0 },
{ name: "ASP.NET", likes: 0, dislikes: 0 },
{ name: "SQL", likes: 0, dislikes: 0 },
{ name: "AngularJS", likes: 0, dislikes: 0 },
];
$scope.technologies = technologies;
$scope.incrementLikes = function (technology) {
$scope.incrementLikes++;
}
$scope.incrementDisLikes = function (technology) {
$scope.incrementDisLikes++;
}
};
myApp.controller("myController", myController);
我收到以下错误:Error:$ injector:modulerr 模块错误。我是angularjs的新手并且正在尝试学习事件处理。点击按钮,数字会增加,同样不喜欢。
答案 0 :(得分:2)
这是因为你在HTML中有这个:
<body ng-app="MyModule">
然而,您已将应用模块定义为:
var myApp = angular.module("FirstModule", []);
您需要更改它们,使它们既可以是“MyModule”,也可以是“FirstModule”。
<强>更新强>
所以你已经纠正了模块注入错误,但也有这个错误:
$scope.incrementLikes = function (technology) {
$scope.incrementLikes++;
}
$scope.incrementDisLikes = function (technology) {
$scope.incrementDisLikes++;
}
应该是:
$scope.incrementLikes = function (technology) {
technology.likes += 1;
}
$scope.incrementDisLikes = function (technology) {
technology.dislikes += 1;
}
您可能还想将第二个按钮的值更改为“不喜欢”而不是“喜欢”。
相关代码,HTML优先:
<div ng-app="FirstModule" ng-controller="myController">
<table>
<thead>
<tr>
<th>Name</th>
<th>Likes</th>
<th>DisLikes</th>
<th>Likes/Dislikes</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="technology in technologies">
<td>{{ technology.name}}</td>
<td>{{ technology.likes}}</td>
<td>{{ technology.dislikes}}</td>
<td>
<input type="button" value="Like" ng-click="incrementLikes(technology)" />
<input type="button" value="Dislike" ng-click="incrementDisLikes(technology)" />
</td>
</tr>
</tbody>
</table>
</div>
使用Javascript:
var myApp = angular.module("FirstModule", []);
var myController = function($scope) {
var technologies = [{
name: "C#",
likes: 0,
dislikes: 0
}, {
name: "ASP.NET",
likes: 0,
dislikes: 0
}, {
name: "SQL",
likes: 0,
dislikes: 0
}, {
name: "AngularJS",
likes: 0,
dislikes: 0
}, ];
$scope.technologies = technologies;
$scope.incrementLikes = function(technology) {
technology.likes += 1;
}
$scope.incrementDisLikes = function(technology) {
technology.dislikes += 1;
}
};
myApp.controller("myController", myController);