Angularjs 如何调用声明到控制器中的函数并需要将其调用到app.run块中?

Angularjs 如何调用声明到控制器中的函数并需要将其调用到app.run块中?,angularjs,Angularjs,我已经在pageChanged中编写了一个函数,并将其转换为控制器。我必须将此函数调用到app.run块中。我提到的参数是$rootScope、$scope等。 它给我的错误是类型错误。 当我试图在app.run块中实现浏览器后退按钮的逻辑时,它给了我一个错误。 我的代码中通过注释提到了错误行。 我的代码在这里: var app=angular.module('myApp', ['ngRoute','ngCookies','ui.bootstrap','ui.router','ngStorage

我已经在pageChanged中编写了一个函数,并将其转换为控制器。我必须将此函数调用到app.run块中。我提到的参数是$rootScope、$scope等。 它给我的错误是类型错误。 当我试图在app.run块中实现浏览器后退按钮的逻辑时,它给了我一个错误。 我的代码中通过注释提到了错误行。 我的代码在这里:

var app=angular.module('myApp', ['ngRoute','ngCookies','ui.bootstrap','ui.router','ngStorage']);
    console.log("in appnew.js")

    app.config(function($routeProvider,$locationProvider,$httpProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider
        .when('/',{
            templateUrl:  'login_admin.html'

        })

        .when('/add',{
            templateUrl: 'add_brands.html',
            controller: 'dashCtrl',
            authenticated: true,
            reloadOnSearch: false

        })



        .otherwise({
            redirectTo: "/"
        });
    });


    app.factory('userModel', function($http,$cookies,$location){
        var userModel={};

        userModel.login= function(loginfrm){
          console.log("loginfrm"+loginfrm.user_name);
          $http.post("http://.............../admin_login",loginfrm).
          success(function(response){
            if (response.success == 1) {
                console.log("Password Matched");
                $cookies.put('user_name',loginfrm.user_name);
                $cookies.put('token',response.token);
                $location.path('/dashboard');
            } else if (response.success == -1) {
                console.log("Password Not Matched");
            } else {
                console.log("Sorry there is some error");

            }
           /*console.log('$scope.dynamic1: %j', $scope);*/
           console.log("response success: %j",response)

          }).
          error(function(response){
            console.log("response error:",response);
          });
        };
        userModel.getAuthStatus = function(){
          var status = $cookies.get('user_name');
          console.log('status: %j', status);
          if(status){
            return true;
          }
          else{
            return false;
          }
        };
        console.log('userModel.getAuthStatus'+userModel.getAuthStatus());
        userModel.doUserLogout = function(){
          $cookies.remove('user_name');
           $cookies.remove('token');
        }
        console.log("userModel: %j",userModel);
        return userModel;
    });




    app.filter('startFrom',function(){
       return function(data,start){
          if(data != null) {
           //console.log("data fetched");
           //console.log('data: %j',data);
           return data.slice(start);
           }
          else if(data == null){ console.log("data is null"); }
       }
    });

    /************************DASH-CONTROLLER************************/
     var st1;
     var st2;
    app.controller('dashCtrl', function($rootScope,$scope,$http,$cookies,$localStorage,$filter,$routeParams,$location,$window){
        console.log('inside dashctrl');

       $scope.users = [];
       $scope.pageSize=10;
      // $scope.currentPage=1;
       if($location.search().page!=undefined){

           $scope.currentPage=$location.search().page;
       }
       else{
           $scope.currentPage=1;
       }

       $scope.check = function(){
            var mobilereg = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/;
            var digitreg = /^\d+$/;
            var dashno={
                         user_name:  $cookies.get('user_name'),
                         token: $cookies.get('token')

                    };
                    if ($location.search().mobile_no==undefined) {
                        console.log("$scope.dash.mobile")
                        dashno.mobile_no=$scope.dash.mobile;

                    } else {
                        dashno.mobile_no=$location.search().mobile_no;//........
                    }

                    $scope.mobile_no = dashno.mobile_no;
                    if(mobilereg.test($scope.mobile_no) && digitreg.test($scope.mobile_no)){
                       $scope.dashform1hide = true;
                       /*$scope.showDetails=false;*/


                        $http.post('http://-------------/get_user_info', dashno).
                        success(function(data,status,header,config){
                        console.log("data: %j", data);
                        if(data.success == 1){
                            console.log("check fn ...............");
                            if ($location.search().mobile_no==undefined) {
                            $location.url('?mobile_no=' + $scope.dash.mobile );

                            }
                            $scope.showDetails=true;

                            $scope.email_id = data.email_id;
                            $scope.user_name = data.user_name;
                            $scope.default_vpa = data.default_vpa;
                            $scope.def_vpa_name = data.def_vpa_name;
                            //$scope.ab;
                            /*if($location.search().page!=undefined){
                                 $scope.ab=true;   //fetchedTrans();
                                 //$scope.currentPage=$location.search().page;
                                 console.log('inside check $scope.currentPage: ', $scope.currentPage);
                                 fetchedTrans();
                                 //$scope.pageChanged($location.search().page);
                            }
                            else{
                                $scope.ab=false;
                                fetchedTrans();
                            }*/
                            fetchedTrans();

                        }else if (data.success == -1) {
                            //mobile no. not exist
                            document.getElementById("msgfornx").innerHtml="Mobile no. does not exist";
                        }
                         else{
                             console.log('check in else')
                         }
                        }).
                        error(function(data,status,header,config){
                            console.log("data"+data);
                            console.log('status'+status);
                            console.log('header'+header);
                            console.log('config: %j',config);
                            alert("something wrong");
                        })
                    };
       }




            console.log('$location.search().mobile_no'+$location.search().mobile_no);
            //console.log('$scope.mobile_no'+$rootScope.mobile_no);
             //console.log("$scope.email_id"+$scope.email_id);

            if($location.search().mobile_no!=undefined){

                    $scope.check();
            }
            else{
                console.log("check not called");
            }


      $scope.mobRegex=/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/;
      $scope.regdigit = /^\d+$/;

        $scope.pageChanged = function(currentPage) {
            console.log('$scope.currentPage: '+ $scope.currentPage);
            console.log('currentPage: ', currentPage);

            st1=$location.search().page;
            console.log("$location.search().page beore updating url"+st1);


            /*if($scope.ab){
                *//*currentPage=$location.search().page;*//*
                //$scope.currentPage=$location.search().page;
                $scope.currentPage=currentPage;
                console.log('currentPage in if: ', currentPage);


            } else {
                $scope.currentPage=currentPage;
                console.log('currentPage in else: ', currentPage);
            }*/
           // st1=$location.path('/add').search({ mobile_no: $location.search().mobile_no, page: $scope.currentPage});

            $scope.currentPage=currentPage;

            $location.path('/add').search({ mobile_no: $location.search().mobile_no, page: $scope.currentPage});
           // st2=$location.path('/add').search({ mobile_no: $location.search().mobile_no, page: $scope.currentPage});
            st2=$location.search().page;
            console.log("$location.search().page after updating url"+st2);




            console.log("$scope.users[($location.search().page-1)*10]"+$scope.users[($location.search().page-1)*10]);

            if($scope.users[($location.search().page-1)*10]==undefined){
               fetchedTrans();
            }
            else{
               console.log("data came aleady");
            }
        };
    });

        /*******************END OF DASH-CONTROLLER***********************/
   app.run(function($rootScope,$location,$scope,userModel,$window,$routeParams,$route){
        $rootScope.$on('$routeUpdate', function(event, next, current){
            console.log("event: %j",event);
            console.log("next: %j",next);
            console.log('current: %j',current);


            //$rootScope.previousLocation=st2;
            console.log("$rootScope.previousLocation"+$rootScope.previousLocation);
            /*if($rootScope.previousLocation == $location.path()) {
                 console.log("Back Button Pressed");
            }

            $rootScope.previousLocation = $rootScope.actualLocation;*/
            if($location.search().mobile_no!=undefined && $location.search().page!=undefined){

                        //if($window.history.back()){
                        console.log("st1 "+st1);
                        console.log("st2 "+st2);
                        if(history.length>=1){
                            st2=st1;
                            $rootScope.pageChanged(st2); //showing error at this line
                            $scope.$apply();
                        }

                      }
            $rootScope.actualLocation = $location.path();

            console.log('$rootScope.actualLocation'+$rootScope.actualLocation);
            //$location.url('/dashboard').replace(undefined);
            console.log('$location.url()'+$location.url());
            console.log('$location.url().replace()'+$location.url().replace());

          if (next.$$route.authenticated) {
              console.log('userModel.getAuthStatus app.run if 1: %j',userModel.getAuthStatus());


            if (!userModel.getAuthStatus()) {
                console.log("getAuthStatus ",!userModel.getAuthStatus);
                console.log('userModel.getAuthStatus app.run if 1(1)'+userModel.getAuthStatus());
                $location.path('/');
            }
          }

          if (next.$$route.originalPath =='/') {
              console.log("next.$$route.originalPath  "+next.$$route.originalPath);
              /*console.log("current.$$route.originalPath  "+$route.current.$$route.originalPath);*/
                if (userModel.getAuthStatus()) {
                                console.log("current "+current);
                                console.log("next "+next);
                                next.$$route.originalPath = '/dashboard';
                                $location.path(next.$$route.originalPath);
                                $location.url('/dashboard').replace(undefined);
                                //current.$$route.originalPath = next.$$route.originalPath;
                                //current.$$route.originalPath = '';
                            } else {

                            }
            }
        });

    });

如果我正确理解了您的问题,我可以想到的一种方法是将pageChanged函数附加到控制器中的$rootScope,如下所示

angular.module('app')
    .controller('AppController', function ($rootScope){
        $rootScope.pageChanged = function(){
            <your_code> 
        }  
});
然后将$rootScope注入app.js中的app.run块,并将pageChanged函数调用为$rootScope.pageChanged


但是,除非您共享一个代码片段,否则很难知道这是您要求的还是导致您提到的错误的原因。

共享代码会很有帮助如果在应用程序运行时创建控制器,为什么不在创建控制器时调用该函数呢?@JEETADHIKARI是对的,你们需要在我的代码中发布你们的代码。当我按下浏览器返回按钮时,我无法调用pageChanged方法。我能有什么解决办法吗。。!你好@ami91我已经添加了我的代码。请看一看。在我的代码中,当我按下浏览器后退按钮时,我无法调用pageChanged方法。我能有什么解决办法吗@sumitkumar您是否尝试将“dashCtrl”控制器中的pageChanged函数附加到$rootScope而不是我在回答中提到的$scope?我看到您已将该函数附加到控制器中的$scope,但您正在使用$rootScope从app.run调用它。这将不起作用,您将看到类似UncaughtTypeError的内容:$rootScope.pageChanged不是函数。这就是你看到的错误吗?