2013-11-01 40 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