Linesofcode
Linesofcode

Reputation: 5903

Call function from another Controller in another file AngularJS

Call function from another Controller Angular Js

Call function from another controller Angularjs

http://tutorials.jenkov.com/angularjs/dependency-injection.html

I've been googling around and trying to adapt but I can't figure out. I have two files: home.js and auth.js. I created the file auth.js because I will need to call the functions inside of it in lot of files.

I can't create simple functions like:

function isAuthed(){
  return true;
}

Because I'll need to use some AngularJS modules, such as HTTP, therefore I believe I need to create a decent angular js file. For what I've read so far, in order to call a function from another controller the best and correct way is to use Services.

home.js

var app = angular.module('home', [
    'ngRoute'
]);

app.controller('home', ['$scope', 'authSERVICE', function($scope, authSERVICE){
    console.log(authSERVICE.hasCredentials());
}]);

auth.js

var app = angular.module('auth', []);

app.service('authSERVICE', ['$http', function($http){

    this.hasCredentials = function(){

        if(window.localStorage.getItem('email') != null && window.localStorage.getItem('password') != null){
            return true;
        }   
    }

    this.login = function(email, password){

        // Base64 function is from a simple JS file.
        var auth = Base64.encode('username:password');

        $http.get('http://localhost/project/api/webservice/getCategories', {

            headers: { 'Authorization': 'Basic ' + auth },
            params : {
                email: email,
                password: password,
            }

        }).success(function(response){

            return true;

        }).error(function(response){

            return false;

        }); 
    }
}]);

This does not work and I receive an error on console poiting to: https://docs.angularjs.org/error/$injector/unpr?p0=authSERVICEProvider%20%3C-%20authSERVICE I kind of understand what's the error information telling me. Although, I still need and want to have two different files.

EDIT: Btw, in the index.html file I've called the scripts:

<script type="text/javascript" src="application/controllers/home.js"></script>
<script type="text/javascript" src="application/controllers/auth.js"></script>

Upvotes: 0

Views: 4302

Answers (1)

Linesofcode
Linesofcode

Reputation: 5903

Thanks to @Ved answer I manage to figure it out. Solved.

var app = angular.module('home', [
    'ngRoute',
    'auth'
]);

Upvotes: 2

Related Questions