链接不同文件的服务

时间:2014-12-11 06:48:59

标签: angularjs service

我有以下代码:

JS:

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

    myApp.controller('myCtrl', function($scope) {


    $scope.ddSelectOptions = [
      {
        text: 'Option1',
        iconCls: 'someicon'
      },
      {
        text: 'Option2',
        someprop: 'somevalue'
      },
    {
        // Any option with divider set to true will be a divider
        // in the menu and cannot be selected.
        divider: true
    },
    {
        // Example of an option with the 'href' property
        text: 'Option4',
        href: '#option4'
    }
];

    $scope.ddSelectSelected = {}; // Must be an object
   });  

并在DataStoreService.js中:

var myApp = angular.module('app');
myApp.factory('dataStoreService', ['$rootScope', function ($rootScope) {

    var service = {

         model: {
            name: '',
            email: ''
       },

        SaveState: function () {
             sessionStorage.userService = angular.toJson(service.model);
        },

        RestoreState: function () {
            service.model = angular.fromJson(sessionStorage.userService);
       }
    }

     $rootScope.$on("savestate", service.SaveState);
     $rootScope.$on("restorestate", service.RestoreState);

    return service;
   }]);

但是,我收到以下错误:

https://docs.angularjs.org/error/ $ injector / nomod?p0 = dataStoreService - 模块'dataStoreService'不可用!您要么错误拼写了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。

我该如何解决?如何将不同文件中的不同控制器和服务链接到我的应用程序?

3 个答案:

答案 0 :(得分:1)

这里,

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

你不需要'dataStoreService'定义为依赖关系,它不是module只是service,所以如果你需要service里面的controller controller将其注入 myApp.controller('myCtrl', function($scope,dataStoreService) { .... ,如下所示,

{{1}}

答案 1 :(得分:1)

将其注入控制器而不是应用程序:

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

myApp.controller('myCtrl', ['$scope', 'dataStoreService', function($scope, dataStoreService) { ....

答案 2 :(得分:1)

<强> app.js

// Declare the main module
var myApp = angular.module('myApp', []);
myApp.controller('Ctrl1', ['$scope', 'MyService', '$window', function($scope, MyService, $window) {

    var str = MyService.getHello();
    $window.alert(str);
}]);

<强> aService.js

angular.module('myApp').
    service('MyService', function() {



        return {
          getHello: function () {
                    return 'hello';
                },

        }
    }
);

<强>的index.html

<!DOCTYPE html>
<html ng-app="myApp">
  <head>

  </head>
  <body>

    <p>An example showing how to share data between controllers using a service</p>    
    <div ng-controller="Ctrl1">
        <h2>Controller 1 Says:</h2>
    </div>

    <script src="http://code.angularjs.org/1.2.1/angular.js"></script>
    <script src="app.js"></script>
    <script src="aService.js"></script>
  </body>

</html>