Routing issue with ui-router in ionic (AngularJS)

五迷三道 提交于 2019-12-13 20:15:57

问题


I have UI routes defined in ionic, and made a console.log in controller, but my problem is when I switch between URLs using ng-href="/#/LINK" then no data displayed in console, but when I refresh the same page I am able to see the data in console .... let me know what I am doing wrong here.

Routes -

  .state('app.roomone', {
    url: "/roomone/:id",
    views: {
      'menuContent': {
        templateUrl: "templates/roomone.html",
        controller: 'RoomoneCtrl'
      }
    }
  })

  .state('app.roomtwo', {
    url: "/selecroom/:roomname/:roomindex",
    views: {
      'menuContent': {
        templateUrl: "templates/roomtwo.html",
        controller: 'RoomtwoCtrl'
      }
    }
  })

Following are my controllers -

.controller('RoomoneCtrl', function($scope, $rootScope) {
  console.log("I am in room one");
});

.controller('RoomtwoCtrl', function($scope, $rootScope) {
  console.log("I am in room two");
});

In my template - I am having simple -- <a ng-href="/#/roomone/MY_ID" />Dummy Link</a>

Problem - Only on refresh(F5) I am getting console values like ""I am in room one"" not on simple navigation of link. Let me know what I am doing wrong.


回答1:


As pointed out in the comments: the view is cashed and therefore the controller is not initialized the second time you visit the page.

One solution was not mentioned in Template does not update when using ui-router and ion-tabs. (change cashing to false in view or in router) therefor I adding an extra answer here (better was adding it to comments but with the code example this would become unclear)

Listen in your controller (or directive) to the $ionicView.beforeEnter event to know when a view is active.

.controller('RoomoneCtrl', function($scope, $rootScope) {
    $scope.$on('$ionicView.beforeEnter', function () {
        // (on first time added to DOM and after the view becomes active after cached
        // change some value on your scope
        $scope.date = new Date();
        console.log("I am in room one");
    });
});

For ionic view events see: http://ionicframework.com/docs/api/directive/ionView/




回答2:


I am also faced the same issue. This is a cache issue. I have fixed the issue by using cache : false.You have have add it in your route as the below,

.state('app.roomone', {
    url: "/roomone/:id",
    cache : false,
    views: {
      'menuContent': {
        templateUrl: "templates/roomone.html",
        controller: 'RoomoneCtrl'
      }
    }
  })

  .state('app.roomtwo', {
    url: "/selecroom/:roomname/:roomindex",
    cache : false,
    views: {
      'menuContent': {
        templateUrl: "templates/roomtwo.html",
        controller: 'RoomtwoCtrl'
      }
    }
  })


来源:https://stackoverflow.com/questions/29792166/routing-issue-with-ui-router-in-ionic-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!