【问题标题】:Correct way to make a factory module in angularJs在angularJs中制作工厂模块的正确方法
【发布时间】:2014-08-07 02:50:55
【问题描述】:

我有一个这样的控制器功能:

$scope.localTimezone = function (userTimezone,datetime) {
  // ....
  return data;
}

使它成为工厂模块的正确方法是什么?我尝试了以下方法,但它给出了错误。

angular.module('localTimezone',  [])
   .factory('localTimezone',function(userTimezone,datetime) {
      // ...
      return data;
   });


angular.module('app', ['localTimezone'])
   .controller('tasksController',function ($scope,localTimezone) {
     // ...
   });

我错过了一些概念或逻辑。谁能指出我正确的方向?

【问题讨论】:

标签: angularjs angularjs-factory


【解决方案1】:

控制器示例 不好:

function MainCtrl () {
  this.doSomething = function () {

  };
}
angular
  .module('app')
  .controller('MainCtrl', MainCtrl);

好:

function MainCtrl (SomeService) {
  this.doSomething = SomeService.doSomething;
}
angular
  .module('app')
  .controller('MainCtrl', MainCtrl);

工厂示例 不好:

function AnotherService () {

  var someValue = '';

  var someMethod = function () {

  };

  return {
    someValue: someValue,
    someMethod: someMethod
  };

}
angular
  .module('app')
  .factory('AnotherService', AnotherService);

好:

function AnotherService () {

  var AnotherService = {};

  AnotherService.someValue = '';

  AnotherService.someMethod = function () {

  };

  return AnotherService;
}
angular
  .module('app')
  .factory('AnotherService', AnotherService);

有关详细指南,请参阅此博客: Opinionated AngularJS styleguide for teams

【讨论】:

  • 假设我想要 $http ...你如何注入到另一个服务?
  • app.service('', ['$http', function($http) { this.yourVar = function() { ... } }]);
  • 对不起,我解释得不好,你如何在有函数AnotherService(){ ........}的好方法中注入 -.... angular.module(' app').factory('AnotherService',AnotherService);
【解决方案2】:

这是一个工作代码示例,假设 userTimezone 和 datetime 是 localTimezone 模块的一部分。

以下内容已修改

  • 您的工厂返回的“数据”已被修改为根据工厂模式返回一个字符串 - 因为您返回的“数据”没有引用任何内容
  • 构建应用程序已移至顶部。这段代码应该在其他任何事情之前执行。
  • app 变量已删除 - 我不喜欢全局变量。

代码:

angular.module('app', ['localTimezone']);

angular.module('localTimezone', []).factory('localTimezone',
  function(userTimezone, datetime) {
    var data = 'hello';
    return { data: data } ;
  });

angular.module('localTimezone').service('userTimezone', function() {
});

angular.module('localTimezone').service('datetime', function() {
});

angular.module('app').controller('tasksController',function ($scope,localTimezone) {
});  

Codepen:http://codepen.io/anon/pen/wijmb(控制台中没有出现错误)

查看http://angular-tips.com/blog/2013/08/understanding-service-types,了解有关 Angular 中不同服务类型的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多