离子:页面上的方法调用输入

C.M*_*.M. 7 navigation angularjs angular-ui-router ionic

我有一个

< ion-side-menu >
链接到我在此处定义的页面:

    app.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

      $stateProvider.state('content', {
        url: "/content",
        abstract: true,
        templateUrl: "templates/sidemenu.html",
        controller: 'SideController'
      });

      $stateProvider.state('content.home', {
        url: "/home",
        views: {
          'menuContent': {
            templateUrl: "templates/home.html",
            controller: "HomeController"
          }
        }
      });

      $stateProvider.state('content.nearby', {
        url: "/nearby",
        views: {
          'menuContent': {
            templateUrl: "templates/nearby.html",
            controller: "NearbyController"
          }
        }
      });

      $stateProvider.state('content.map', {
        url: "/map",
        views: {
          'menuContent': {
            templateUrl: "templates/map.html",
            controller: "MapController"
          }
        }
      });

      $stateProvider.state('content.radar', {
        url: "/radar",
        views: {
          'menuContent': {
            templateUrl: "templates/radar.html",
            controller: "RadarController"
          }
        }
      });

      $stateProvider.state('content.location-details', {
        url: "/location-details/:index",
        views: {
          'menuContent': {
            templateUrl: "templates/location-details.html",
            controller: "DetailsController"
          }
        },
        resolve: {
          currentLocation: function($stateParams, shareService, NearbyFactory)
          {
            return NearbyFactory.getLocations()[$stateParams.index];
          }
        }

      });

      $urlRouterProvider.otherwise("/content/home");
    });
Run Code Online (Sandbox Code Playgroud)

我希望在用户导航到此页面时以及在页面离开时(在加载AJAX数据或开始收听某些Cordova传感器时)在我的控制器中执行一个方法.像这样:

    app.controller("HomeController", function()
    {
      $scope.onEnter = function(previous_page)
      {
       ...
      };

      $scope.onExit = function(next_page)
      {
       ...
      };
    });
Run Code Online (Sandbox Code Playgroud)

我已经在$ stateProvider状态中尝试了onEnter和onExit但是afaik我没有我的$ scope.

获得此功能的最简单/最好/最好的方法是什么?如果我可以确定上一页/下一页并且用户是否向前/向前导航,那将是很好的.我试过这个:

$scope.$on('$routeChangeStart', function(event, next, current)
{
 console.log(next);
});
Run Code Online (Sandbox Code Playgroud)

但这并不是每次都有效,加载页面时它不会触发.这对我来说似乎有点脏,因为我必须在每个控制器中实现它.

谢谢!

小智 6

您可以使用$ ionicView.beforeEnter和beforeLeave.只需将其添加到您的HomeController:

   app.controller("HomeController", function()
{
        $scope.$on('$ionicView.beforeEnter', function() {
           //do stuff before enter

        });
         $scope.$on('$ionicView.beforeLeave', function() {
           //do your stuff after leaving

        });
});
Run Code Online (Sandbox Code Playgroud)

你可以在这里查看$ ionicView的文档.