Angular JS创建对象
Angular JS create object
我是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<-训练计划
一个想法我做错了什么?
感谢
是的,问题是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
视为您试图注入到工厂中的提供程序,从而导致错误。请参阅此处(工厂配方部分)了解更多信息。
相关文章:
- 在创建对象后附加一个jquery事件
- 错误:自动化服务器可以't创建对象
- 如何在JS中创建对象的可变和不可变副本
- Jasmine在全局窗口对象上创建本地JS函数的Spy
- 如何在Node.js中从数组中的值创建对象
- 使用 eval() JS 动态创建对象
- JS使用构造函数在对象中创建对象
- 在 JS 中创建对象
- 在默认情况下将可枚举设置为 false 的 JS 中创建对象属性的其他方法是什么
- JS:使用迭代器在循环中创建对象
- Angular JS创建对象
- THRE.JS动态创建对象
- js代码在创建对象的新实例后显示错误
- 通过JS中的对象构造函数创建对象,该构造函数位于单独的JS文件中
- 通过使用iffe和构造函数在js中创建对象
- 可以't使用Openshift创建node.js Web服务器.对象#<对象>没有方法'听我
- 如何在动能js中创建一个普通的html5文本框,而不创建对象“;运动的文本”;
- 根据处理速度创建对象的运动.js
- 从 for 循环的输出创建一个 js 对象
- 如何从DLL中创建对象并使用edge.js调用其方法之一