Angular JS创建对象

Angular JS create object

本文关键字:创建对象 JS Angular      更新时间:2023-09-26

我是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:unp]未知提供程序:argsProvider<-args&lt-训练计划

一个想法我做错了什么?

感谢

是的,问题是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);创建一个实例

您需要向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视为您试图注入到工厂中的提供程序,从而导致错误。请参阅此处(工厂配方部分)了解更多信息。