2013-11-01 44 views
3

我准备使用AMD(require.js)的锅炉Angular应用程序。到目前为止,我得到了它的工作,但我有服务问题。我如何结合服务?使用Require.js在Angular中创建服务

这是Main.js:

require.config({ 

paths: { 
// These are the core components - without which our application could not run 
angular: '../lib/angular/angular', 
angularResource: '../lib/angular/angular-resource', 

// These are components that extend our core components 
jquery: '../lib/jquery/jquery-1.8.2.min', 
bootstrap: '../lib/bootstrap/js/bootstrap', 
underscore: '../lib/underscore/underscore', 

text: '../lib/require/text' 

}, 
    shim: { 
    'angular' : {'exports' : 'angular'}, 
    'angular-resource' : {deps:['angular']}, 
    'bootstrap': {deps:['jquery']}, 
    'underscore': {exports: '_'} 
    }, 
    priority: [ 
    "angular" 
    ], 
    urlArgs: 'v=1.1' 
}); 

require([ 
    'angular', 
    'app', 
    'services/services', 
    'services/dateGetter', 
    'controllers/controllers', 
    'controllers/navbar', 
    'controllers/exampleTemplateController', 
    'filters/filters', 
    'directives/directives', 
    'routes' 
], function(angular, app) { 

    angular.element(document).ready(function() { 
    angular.bootstrap(document, ['myApp']); 
    }); 
}); 

这是我开发的控制器:

define([ 
    'app', 
    '../helpers/exampleFile' //example of importing custom file.js in our controller. 
], 

function(app, exampleFile) { 

    'use strict'; 
    return app.controller('exampleTemplateController', [ 
     '$scope', 'dateGetter', 
     function ($scope) { 
      $scope.sayHello = function(module) { 

       alert("Current Date: " + dateGetter.getCustomDate + " " + exampleFile(module.name)); 

      } 
     } 
    ]); 
}); 

这是我尝试开发服务(失败的悲惨这里):

define([ 
    'app' 
], 

function(app) { 
     'use strict'; 
       debugger; 
     return app.factory('dateGetter', [ 
      '$scope', 
      function ($scope) { 
       $scope.getCustomName = function() { 
        return "THIS IS MY NAME"; 
       } 
      } 
     ]); 
    }); 

我觉得我很接近,但有些东西没有我。

另一个问题是,如果我结束了大量的控制器和服务,我们将...我是否需要在main.js文件中列出每个人和每个人(在require :)下?

回答

2

我得到了现在的服务工作。是我的错。现在,我可以访问它并使用它。

define([ 
    'app' 
], 

function(app) { 
    return app.factory('serviceExample', function () { 

      return { 
       nameOfMethod: function() { 
        return "Is this working"; 
       } 
      } 
     } 
    ); 
}); 

我现在在想什么......我需要使用Angular所需的吗?

我读了很多文章辩论相同的问题,没有简明的答案。 我正在考虑使用require,因为我们之前使用过它,而且这个应用程序无论如何都会成为一个大型编程器。

意见?

+0

您应该使用requireJS进行延迟​​加载或异步加载文件,例如,如果您的应用程序很大。您也可以对缩小或混淆等文件进行优化。 – jamesjara