Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 访问同一工厂中的方法_Angularjs - Fatal编程技术网

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