gpt4 book ai didi

javascript - Angular JS 创建对象

转载 作者:行者123 更新时间:2023-11-28 06:34:12 24 4
gpt4 key购买 nike

我是 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;
});

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

Error: [$injector:unpr] Unknown provider: argsProvider <- args <- WorkoutPlan

知道我做错了什么吗?

谢谢

最佳答案

是的,问题是 args 参数不是有效的可注入(inject)模块,例如 $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 工厂注入(inject) Controller 或指令中,然后使用 WorkoutPlan.create(actualArgs); 创建一个实例

关于javascript - Angular JS 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34432634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com