无法在角度js中注册服务

时间:2018-01-15 11:28:45

标签: javascript angularjs service

我在加载页面时收到以下错误:scripts.js:10

  

未捕获的ReferenceError:未定义SimpleAppService

我的Html页面

batch_input_shape
用于角度脚本的

scripts.js:

<!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>

我的服务

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;
            }
        }
    ]);

我的工厂:

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);
    }
});

1 个答案:

答案 0 :(得分:0)

您正在覆盖每个服务/工厂文件中的模块mainModule

script.js

中仅定义一次模块
var mainModule = angular.module("mainModule", []); 

然后获取它以注册服务并在其他文件 MathFactory.js SimpleAppService.js

中使用它
var mainModule = angular.module("mainModule");

mainModule.service('service' ...);
相关问题