Search code examples
angularjsparameter-passingangularjs-factory

Calling a function from a factory Angularjs


Relatively new still. I'm trying to be able to get and set values from a factory, but I can't seem to get a function to run. It calls a type error. I also can't add $scope to the factory without it killing it. Help?

app.factory('globals', function() {
    var globalTag = {};
        globalTag.currDrive = "";
        globalTag.myFaults = "";
    var availDrives = "";

    globalTag.currDrive = "this sucks";
    globalTag.myFaults = "I've got a lovely bunch of faulty faults";

    function setDrive(driveID) {
        globalTag.currDrive = driveID;
    };

    return globalTag;
});

app.controller('FaultController', ['$scope', '$routeParams', 'globals', function($scope, $routeParams, globals) {
    //Setup dummy paramenters
    $scope.driveInfo = {};
    $scope.driveInfo = globals.setDrive("350");
}]);

Solution

  • You are never expose setDrive methods from the service. Correct code would be:

    app.factory('globals', function () {
        var globalTag = {};
        globalTag.currDrive = "";
        globalTag.myFaults = "";
        var availDrives = "";
    
        globalTag.currDrive = "this sucks";
        globalTag.myFaults = "I've got a lovely bunch of faulty faults";
    
        function setDrive(driveID) {
            globalTag.currDrive = driveID;
        };
    
        globalTag.setDrive = setDrive; // <--- make it part of globals service API
    
        return globalTag;
    });