Angularjs 访问同一工厂中的方法
我的工厂定义如下:Angularjs 访问同一工厂中的方法,angularjs,Angularjs,我的工厂定义如下: mob.factory("OrderHelper", function() { return { lineItemPrice: function(lineItem) { return lineItem.price * lineItem.quantity; }, orderTotal: function(order) { order.items.forEach(function (item)) {
mob.factory("OrderHelper", function() {
return {
lineItemPrice: function(lineItem) {
return lineItem.price * lineItem.quantity;
},
orderTotal: function(order) {
order.items.forEach(function (item)) {
total += lineItemPrice(item);
}
}
}
});
mob.factory("OrderHelper", function() {
var methods = {};
methods.lineItemPrice = function(lineItem) {
return lineItem.price * lineItem.quantity;
};
methods.orderTotal = function(order) {
order.items.forEach(function (item)) {
total += methods.lineItemPrice(item);
}
};
return methods;
});
问题是我不能在“orderTotal”方法中使用“lineItemPrice”方法。
它抛出这个错误:错误:[$interpolate:interr]不能插值:{{orderTotal(order)}
有人能告诉我如何从同一工厂的函数调用方法吗
谢谢。试试这个:
您也可以这样做:
mob.factory("OrderHelper", function() {
return {
lineItemPrice: function(lineItem) {
return lineItem.price * lineItem.quantity;
},
orderTotal: function(order) {
order.items.forEach(function (item)) {
total += lineItemPrice(item);
}
}
}
});
mob.factory("OrderHelper", function() {
var methods = {};
methods.lineItemPrice = function(lineItem) {
return lineItem.price * lineItem.quantity;
};
methods.orderTotal = function(order) {
order.items.forEach(function (item)) {
total += methods.lineItemPrice(item);
}
};
return methods;
});
可以使用angular.foreach()迭代每个项,并提供第三个参数作为回调函数的上下文
mob.factory("OrderHelper", function() {
return {
lineItemPrice: function(lineItem) {
return lineItem.price * lineItem.quantity;
},
orderTotal: function(order) {
var total = 0;
angular.forEach(order.items, function(item) {
total += this.lineItemPrice(item)
}, this); // add `this` as the context of the callback
return total;
}
}
});