angularjs - 无法注入服务
问题描述
我没有抛出任何错误,所以我不知道我的代码有什么问题。当我在浏览器中打开我的 index.html 时,我看不到分数。
索引.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My HTML File</title>
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js">
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.js"></script>
<script src = "app.js"></script>
</head>
<body ng-app = "app">
<p ng-controller="ScoreController">
Score: {{score.points}}
</p>
<p ng-controller="ScoreController">
<button ng-click="increment()">Increment</button>
</p>
</body>
</html>
应用程序.js:
angular.module('app', [])
.value('randomScore', function(){
return Math.ceil(Math.random() * 10);
});
angular.module('app').controller('ScoreController', ['randomScore', function
($scope, score, randomScore){
$scope.score = score;
$scope.increment = function(){
$scope.score.points += randomScore();
};
}]);
解决方案
所以事实证明我缺少分数构造函数和分数服务:
得分constructor.js:
function Score(randomScore){
this.points = randomScore();
}
评分-service.js:
angular.module('app')
.service('score', Score);
添加这两个文件并修复@Aleksey Solovey 在评论中指出的问题修复了这个问题。
推荐阅读
- javascript - 任何链接都可以在评论部分点击
- console - #10 #13 在控制台行的末尾!在上海
- c++ - 如何在 C 或 C++ 中将字符转换为整数
- bash - 在 bash 别名设置中指定输入参数的范围
- php - $_SESSION 变量未设置值
- html - 通过共享网站链接共享信息
- android - 从广播接收器在 AlarmManager 事件上启动 Activity
- java - 如何根据日期对“MMM YYYY”日期字符串进行排序?
- javascript - 为什么我的 Chrome 扩展在性能分析期间更快?
- javascript - 如何将“标题”和“艺术家”发送到外部 xml 文档?