我是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< - WorkoutPlan
一个想法,我做错了什么?
由于
答案 0 :(得分:0)
您需要向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(工厂配方部分)。
答案 1 :(得分:0)
是的,问题是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);
创建实例