Search code examples
angularjsangularjs-service

Unable to inject service


I don't get any errors thrown, so I don't know what is wrong with my code. When I open my index.html in the browser I don't see the score.

index.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>

app.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 !image1


Solution

  • So it turns out I was missing score-constructor and score-service:

    score-constructor.js:

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

    score-service.js:

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

    adding these 2 files and also fixing the problem @Aleksey Solovey pointed to in the comments fixed this issue.