0

The idea was to write a simple service which multiplies 2 numbers, then pass it to a controller and display it in a html page. However, I can't seem to get the result to be displayed, as it simply shows {{product}}.

  • EDIT: When i move the object into the same file as the services, it works. However, when i put it in a separate file (in the same folder) called objects.js, it's like it stops being visible to the services, and no longer works. I would like to make it work like that.

Here's all the parts of the code:

  • JavaScript object:

    function Multiplier(valueFactor) {
     this.multiply = function (controllerFactor) {
      return valueFactor * controllerFactor;
     };
    }
  • Services:

var services = angular.module("services",[]);
services.value('factor',6);
services.service('multiplier',['factor', Multiplier]);
  • Controller:

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

app.controller('multiplyController',['$scope','multiplier', function($scope,multiplier) {
 $scope.product = multiplier.multiply(2);
}]);
  • HTML page:

<!DOCTYPE html>
<html ng-app="app">
 <head>
 
 </head>
 <body>
  <div ng-controller="multiplyController">
   {{product}}
  </div>
  
  <script src="js/angular.js"></script>
  <script src="js/angular-route.js"></script>
  <script src="js/jquery.min.js"></script>
  
  <script src="app/app.js"></script>
  <script src="app/controllers.js"></script>
  <script src="app/services.js"></script>
  
 </body>
</html>
newdev
  • 59
  • 1
  • 6
  • Possible duplicate of [Pass Javascript variables to Angularjs controller](https://stackoverflow.com/questions/32979504/pass-javascript-variables-to-angularjs-controller) – bigless Jan 18 '18 at 04:15

2 Answers2

0

You are calling angular here var app = angular.module("app",['services']); You should use the app variable for the rest of your code, for example:

app.controller('mycontrl', [function(){/*...*/}])

app.service('mysrvc1', [function(){/*...*/}])

app.service('mysrvc2', [function(){/*...*/}])

app.factory('myfact', [function(){/*...*/}])

You just install once the angular.module()

Fernando Carvajal
  • 1,869
  • 20
  • 19
0
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Test</title>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<script>
var app = angular.module("app",[]);

function Multiplier(valueFactor) {
        this.multiply = function (controllerFactor) {
            return valueFactor * controllerFactor;
        };
    }

app.value('factor',6);
app.service('multiplier',['factor', Multiplier]);

app.controller('multiplyController',['$scope','multiplier', function($scope,multiplier) {
    $scope.product = multiplier.multiply(2);
}]);
  </script>
</head>
<body ng-app="app">
 <div ng-controller="multiplyController">
            {{product}}
        </div>
</body>
</html>