Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, call service function from current service

I have service called "sharedData" with some functions, how to call one of these functions from another such functions? here the code(marked trouble functions with "???????"): Thanks

service('sharedData', function ($http) {
    var refillList = [];
    var orderCart = {
        orderPlace: null,
        orderList: [],
        totalSum: 0
    };

    return {
        ....
        addRefill: function(value) {
           ...here some logic....
        },

        addOrder: function(order) {
            ...here some logic....
        },
        sendOrder: function(order, refill) {
            $http.get(config.urls.ajaxOrder + "{\"order\":{\"table_id\":" + orderCart.orderPlace + ",\"item_id\":" + order.id + ",\"amount\":1,\"action\":1}}").success(function(dataDetails) {
                if (dataDetails.success) {
                    if (refill == 1) {
                        // Filling refill list
                        ??????????????????this.addRefill(order);?????????
                    }
                    // Filling order cart
                    ?????????this.addOrder(order);?????????????
                }
            });
        }
    };
}).
like image 700
Simcha Avatar asked May 30 '13 14:05

Simcha


Video Answer


1 Answers

You should save reference to this.

var self = this; is a common practice.

sendOrder: function(order, refill) {
    var self = this;
    $http.get(config.urls.ajaxOrder + "{\"order\":{\"table_id\":" + orderCart.orderPlace + ",\"item_id\":" + order.id + ",\"amount\":1,\"action\":1}}")
        .success(function(dataDetails) {
            if (dataDetails.success) {
                if (refill == 1) {
                    // Filling refill list
                    self.addRefill(order);
                }
                    // Filling order cart
                    self.addOrder(order);
                }
            }
        });
    }

Update 2016

Now, with ES6 you can use arrow functions like this:

sendOrder: function(order, refill) {
    $http.get(config.urls.ajaxOrder + "{\"order\":{\"table_id\":" + orderCart.orderPlace + ",\"item_id\":" + order.id + ",\"amount\":1,\"action\":1}}")
        .success(dataDetails => {
            if (dataDetails.success) {
                if (refill == 1) {
                    // Filling refill list
                    this.addRefill(order);
                }
                    // Filling order cart
                    this.addOrder(order);
                }
            }
        });
    }

Arrow functions doesn't change a context, so this will be the same this.

MDN article about arrow functions

like image 164
bniwredyc Avatar answered Nov 06 '22 03:11

bniwredyc