【问题标题】:Call function from another Controller in another file AngularJS从另一个文件AngularJS中的另一个控制器调用函数
【发布时间】:2014-12-31 11:32:29
【问题描述】:

Call function from another Controller Angular Js

Call function from another controller Angularjs

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

我一直在谷歌上搜索并试图适应,但我无法弄清楚。 我有两个文件:home.jsauth.js。我创建了文件auth.js,因为我需要在很多文件中调用其中的函数。

我无法创建简单的函数,例如:

function isAuthed(){
  return true;
}

因为我需要使用一些 AngularJS 模块,例如 HTTP,所以我相信我需要创建一个像样的 Angular js 文件。 就我目前所阅读的内容而言,为了从另一个控制器调用函数,最好和正确的方法是使用 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;

        }); 
    }
}]);

这不起作用,我在控制台指向:https://docs.angularjs.org/error/$injector/unpr?p0=authSERVICEProvider%20%3C-%20authSERVICE 时收到错误消息 我有点明白错误信息告诉我什么。虽然,我仍然需要并且想要拥有两个不同的文件。

编辑:顺便说一句,在index.html 文件中我调用了脚本:

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

【问题讨论】:

    标签: javascript angularjs cordova


    【解决方案1】:

    感谢@Ved 的回答,我设法弄明白了。 已解决

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

    【讨论】:

      猜你喜欢
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 2016-12-16
      • 1970-01-01
      相关资源
      最近更新 更多