【问题标题】:Angular JS create objectAngular JS 创建对象
【发布时间】:2015-12-23 09:41:37
【问题描述】:

我是 AngularJS 的新手,我想使用 Angular 的工厂功能创建一个对象。我的代码是这样的:

angular.module('7minWorkout')
.factory('WorkoutPlan', function(args){
      this.exercises = [];
      this.name = args.name;
      this.title = args.title;
      this.restBetweenExercise = args.restBetweenExercise;
      this.totalWorkoutDuration = function () {
          if (this.exercises.length == 0) return 0;
          var total = 0;
          angular.forEach(this.exercises, function (exercise) {
              total = total + exercise.duration;
          });
          return this.restBetweenExercise * (this.exercises.length - 1) + total;
      }
     return this;
  }); 

尝试运行此程序时出现以下错误:

错误:[$injector:unpr] 未知提供者:argsProvider

一个想法我做错了什么?

谢谢

【问题讨论】:

  • 什么是args?在factory 中创建一个函数并将您的args 传递给它。

标签: javascript angularjs


【解决方案1】:

是的,问题在于args 参数不是有效的可注入模块,例如$scope$http

相反,您可以做的是在内部定义您的类并返回它的一个新实例。这是一个例子:

angular.module('7minWorkout')
.factory('WorkoutPlan', function() {

  var myWorkoutPlan = function(args) {
    this.exercises = [];
    this.name = args.name;
    this.title = args.title;
    this.restBetweenExercise = args.restBetweenExercise;
    this.totalWorkoutDuration = function() {
      if (this.exercises.length == 0) return 0;
      var total = 0;
      angular.forEach(this.exercises, function(exercise) {
        total = total + exercise.duration;
      });
      return this.restBetweenExercise * (this.exercises.length - 1) + total;
    }
  };

  return {
    create: function(args) {
      return new myWorkoutPlan(args);
    }
  };
});

然后,无论您想在哪里使用它,您都可以将 WorkoutPlan 工厂注入到控制器或指令中,然后使用 WorkoutPlan.create(actualArgs); 创建实例

【讨论】:

    【解决方案2】:

    您需要向 Angular 框架声明您的工厂采用参数,如下所示:

    angular.module('7minWorkout')
        .factory('WorkoutPlan', ['args', function(args){
            this.exercises = [];
            this.name = args.name;
            this.title = args.title;
            this.restBetweenExercise = args.restBetweenExercise;
            this.totalWorkoutDuration = function () {
                if (this.exercises.length == 0) return 0;
                    var total = 0;
                    angular.forEach(this.exercises, function (exercise) {
                    total = total + exercise.duration;
                });
            return this.restBetweenExercise * (this.exercises.length - 1) + total;
        }
        return this;
    }]); 
    

    否则,Angular 会将args 视为您尝试注入工厂的提供程序 - 因此会出现错误。请参阅here(工厂配方部分)了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多