服务不在Angular事件处理程序范围内

时间:2014-06-11 05:18:45

标签: javascript angularjs angular-services

我在学习了JavaScript和jQuery之后决定学习Angular.js并且发现它有点粗糙。这是我的代码。

的index.html:

<html>
    <head>
        <title>Resolute</title>
        <script src="js/angular 1.3.0-beta9/angular.js" type="text/javascript"></script>
        <script src="js/index.js" type="text/javascript"></script>
    </head>
    <body ng-app="resoluteApp">
        <form novalidation ng-controller="resoluteCtrl" ng-submit="submit()">
            <button type="submit">Submit</button>
        </form>
    </body>
</html>

index.js:

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

app.service('resoluteService', function myService() {
    this.bar = function() { return 'resolute'; };
});

app.controller('resoluteCtrl', function($scope) {
        $scope.submit = function() {
            alert(resoluteService.bar());  // resoluteService is undefined here
        };
    });

我希望能够从bar()事件处理程序resoluteService中调用服务ng-submit中定义的函数$scope.submit()。按下提交按钮后,我在控制台中收到以下错误(Chrome 35.0.1916.153):

ReferenceError: resoluteService is not defined
    at Scope.$scope.submit (http://localhost:8383/resolute/js/index.js:9:19)
    at http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:10797:21
    at http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:19791:17
    at Scope.$eval (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:12699:28)
    at Scope.$apply (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:12797:23)
    at HTMLFormElement.<anonymous> (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:19790:21)
    at http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:2860:10
    at forEach (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:327:20)
    at HTMLFormElement.eventHandler (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:2859:5) 

由于我仍然试图让我的头脑绕着Angular的做事方式,我不确定如何引导resoluteService或其中的bar函数进入范围$scope.submit。我可能会以完全错误的方式思考它,或者它可能只是一些我想念的简单事物。有关如何解决这个问题的想法吗?

1 个答案:

答案 0 :(得分:1)

您需要将服务注入控制器,

app.controller('resoluteCtrl', function($scope,resoluteService) {

}