问题描述
我在 ionic 中定义了 UI 路由,并在控制器中创建了一个 console.log
,但我的问题是当我使用 ng-href="/#/LINK" 在 URL 之间切换时没有数据显示在控制台中,但是当我刷新同一页面时,我可以在控制台中看到数据......让我知道我在这里做错了什么.
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.
路线 -
.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'
}
}
})
以下是我的控制器 -
.controller('RoomoneCtrl', function($scope, $rootScope) {
console.log("I am in room one");
});
.controller('RoomtwoCtrl', function($scope, $rootScope) {
console.log("I am in room two");
});
在我的模板中 - 我有简单的 - <a ng-href="/#/roomone/MY_ID"/>Dummy Link</a>
In my template - I am having simple -- <a ng-href="/#/roomone/MY_ID" />Dummy Link</a>
问题 - 仅在刷新(F5)时,我得到的控制台值如我在第一个房间",而不是简单的链接导航.让我知道我做错了什么.
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.
推荐答案
正如评论中所指出的:视图被兑现,因此控制器不会在您第二次访问页面时初始化.
As pointed out in the comments: the view is cashed and therefore the controller is not initialized the second time you visit the page.
模板中未提及一种解决方案使用 ui-router 和 ion-tabs 时不会更新.(在视图或路由器中将兑现更改为 false)因此我在这里添加了一个额外的答案(最好将其添加到评论中,但使用代码示例会变得不清楚)
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)
在您的控制器(或指令)中侦听 $ionicView.beforeEnter 事件以了解视图何时处于活动状态.
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");
});
});
有关离子视图事件,请参阅:http://ionicframework.com/docs/api/指令/ionView/
For ionic view events see: http://ionicframework.com/docs/api/directive/ionView/
这篇关于ionic (AngularJS) 中 ui-router 的路由问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!