0

For some reason it gives me the error:

ReferenceError: random is not defined at Scope.$scope.generateRandom

I dont know what im doing wrong, you can go check out the website im using to do this HERE.

index.html:

<!DOCTYPE html>
<html lang= "en">

<head>
    <meta charset="UTF-8" />
    <title>Basic Login Form</title>
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
    <script src = "https://rawgit.com/nirus/Angular-Route-Injector/master/dist/routeInjector.js"></script>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>
    <script type="text/javascript" src="script23.js"></script>
</head>
  <body ng-app = "app" ng-controller = "app">
       <button ng-click = "generateRandom()">Generate Random Number</button>
       <br> {{randomNumber}}
  </body>
</html>

script23.js:

var app = angular.module('app', []);

app.service('random', function(){
    var randomNum = Math.floor(Math.random()*10)
    this.generate = function(){
          return randomNum;
    }

});

app.controller('app' ,  function($scope){
    $scope.generateRandom = function(){
      alert("Something")
        $scope.randomNumber = random.generate();

    }
})

2 Answers2

2

To use service in controller, you need to inject it.

app.controller('app', function ($scope, random) {

I'd recommend you to use following syntax:

app.controller('app', ['$scope', 'random', function ($scope, random) {

See Why we Inject our dependencies two times in angularjs?

Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Still dosent Work , look at my website for edits : http://checkingprojects.netne.net/ –  Dec 31 '15 at 05:26
0

Change your controller like this, since you are using the service 'random'

myApp.controller('app', ['$scope','random', function( $scope,random)
{
    $scope.generateRandom = function(){
      alert("Something")
        $scope.randomNumber = random.generate();

    }
}])

Here is the working Application

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396