运行 每个控制器开头的函数

Run a function on the begining of every Controller

我想 运行 在我拥有的每个控制器的开头添加一个函数,如下所示:

faraWorkspaceApp.controller('AccountController', function () {
    FaraFunctions(); // this function
});

faraWorkspaceApp.controller('DashboardController', function () {
    FaraFunctions(); // this function
});

faraWorkspaceApp.controller('ChangePasswordController', function () {
    FaraFunctions(); // this function
});

将此代码放在哪里,防止在 angular js 中重复 FaraFunctions(); 代码?

由于您使用的是 ui.router ,请改用 stateChangeStart

.run(function($rootScope, $location, $state) {


    $rootScope.$on( '$stateChangeStart', function(e, toState  , toParams
                                                   , fromState, fromParams) {

        var isLogin = toState.name === "login";
        if(isLogin){
           return; // no need to redirect 
        }
    });
});

我找到的最佳方法是 $viewContentLoaded:

faraWorkspaceApp.run(function ($rootScope, $location, $state, $templateCache) {
    $rootScope.$on('$viewContentLoaded', function (e) {
        FaraFunctions();
    });
});