Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : From a factory, how can I call another function

Do I have to move my getTemplates function out of the return or what ?

Example : I dont know what to replace "XXXXXXX" with (I have tried "this/self/templateFactory" etc... ) :

.factory('templateFactory', [
    '$http',
    function($http) {

        var templates = [];

        return {
            getTemplates : function () {
                $http
                    .get('../api/index.php/path/templates.json')
                    .success ( function (data) {
                        templates = data;
                    });
                return templates;
            },
            delete : function (id) {
                $http.delete('../api/index.php/path/templates/' + id + '.json')
                .success(function() {
                    templates = XXXXXXX.getTemplates();
                });
            }
        };
    }
])
like image 655
Purplefish32 Avatar asked Aug 14 '13 14:08

Purplefish32


People also ask

How do you call a function in AngularJS?

You can call your angularJS function from javascript or jquery with the help of angular. element().

Can we call one controller from another controller in AngularJS?

In AngularJS when it comes to communicating between controllers, one would naturally assume to reference another controller you can simply inject it into another controller and call its methods: however, you cannot do that.

Can we call function in HTML in angular?

To invoke this function in the html document, we have to create a simple button and using the onclick event attribute (which is an event handler) along with it, we can call the function by clicking on the button.


1 Answers

By doing templates = this.getTemplates(); you are referring to an object property that is not yet instantiated.

Instead you can gradually populate the object:

.factory('templateFactory', ['$http', function($http) {
    var templates = [];
    var obj = {};
    obj.getTemplates = function(){
        $http.get('../api/index.php/path/templates.json')
            .success ( function (data) {
                templates = data;
            });
        return templates;
    }
    obj.delete = function (id) {
        $http.delete('../api/index.php/path/templates/' + id + '.json')
            .success(function() {
                templates = obj.getTemplates();
            });
    }
    return obj;       
}]);
like image 176
AlwaysALearner Avatar answered Sep 23 '22 08:09

AlwaysALearner