首页 > 解决方案 > 无法注入服务

问题描述

我没有抛出任何错误,所以我不知道我的代码有什么问题。当我在浏览器中打开我的 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();
        };
}]);

index.html-screenshot !image 1

标签: angularjsangularjs-service

解决方案


所以事实证明我缺少分数构造函数和分数服务:

得分constructor.js:

function Score(randomScore){
this.points = randomScore();
   }

评分-service.js:

angular.module('app')
.service('score', Score);

添加这两个文件并修复@Aleksey Solovey 在评论中指出的问题修复了这个问题。


推荐阅读