简体   繁体   中英

unable to register service in angular js

I receiving following error on loading page: scripts.js:10

Uncaught ReferenceError: SimpleAppService is not defined

My Html page

<!DOCTYPE html> <html> <head>   <script src="angular.js"></script>  
<script src="scripts.js"></script>   <script
src="MathFactory.js"></script>   <script
src="SimpleAppService.js"></script>  </head>

<body ng-app="mainModule">   <div ng-controller="simpleController">
    <strong>First name:</strong> {{person.firstName}}<br />
    <strong>Last name:</strong> {{person.lastName}}<br />
    <strong>Full name:</strong> {{getFullName()}}<br />
    <br />
    <label>Set the first name: <input type="text" ng-model="person.firstName"/></label><br />
    <label>Set the last name: <input type="text" ng-model="person.lastName"/></label>   </div> </body> </html>

scripts.js for angular scripts:

angular.module("mainModule", []).value("person", {
    firstName:
    "firstName",
    lastName: "lastName",
    getFullName: function () {
        return firstName + " " + lastName;
    }
})
.service("SimpleAppService", SimpleAppService)
.controller("simpleController", ["SimpleAppService", function
        ($scope, person) {
            $scope.person = person;
            $scope.getFullName =
            function () {
                return person.firstName + person.lastName;
            }
        }
    ]);

My Service

var mainModule = angular.module("mainModule", []);
mainModule.service("SimpleAppService", function (MathFactory) {
    this.square = function (a) {
        return MathFactory.multiply(a, a);
    }
    this.add = function (a, b) {
        return MathFactory.add(a, b);
    }
});

My factory :

var mainModule = angular.module("mainModule", []);

mainModule.factory('MathFactory', function () {
    var factory = {};
    factory.multiply = function (a, b) {
        return a * b;
    }
    factory.add =
    function (a, b) {
        return a + b;
    }
    factory.sub = function (a, b) {
        return a - b;
    }
    return factory;
});

You are overwriting the module mainModule in every service/factory file.

Define the module only once in script.js

var mainModule = angular.module("mainModule", []); 

Then fetch it to register service and use it following in other file MathFactory.js and SimpleAppService.js

var mainModule = angular.module("mainModule");

mainModule.service('service' ...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM