Jor*_*rre 79 angularjs ionic-framework
我正在构建一个带有角度+离子的应用程序,它使用底部带有三个离子标签的经典三键菜单.当用户单击选项卡时,该模板将通过ui-router打开.
我有这样的州:
$stateProvider
.state('other', {
url: "/other",
abstract: true,
templateUrl: "templates/other/other.html"
})
Run Code Online (Sandbox Code Playgroud)
在模板中我做了类似的事情:
<ion-nav-view name="other" ng-init="doSomething()"></ion-nav-view>
Run Code Online (Sandbox Code Playgroud)
我知道我可以在我的控制器中编写doSomething()函数,并在那里手动调用它.这给了我同样的问题.当有人打开那个视图时,我似乎无法弄清楚如何不止一次调用doSomething()函数.
现在,doSomething()函数被调用得很好,但只是第一次用户打开视图/选项卡.每当用户打开该视图或选项卡时,我想调用一个函数(更新地理位置).
实现这一目标的正确方法是什么?
谢谢你的帮助!
Yak*_*idi 86
默认情况下,您的控制器是缓存,这就是您的控制器只触发一次的原因.要关闭某个控制器的缓存,您必须修改.config(..).state并将cache选项设置为false.例如:
.state('myApp', {
cache: false,
url: "/form",
views: {
'menuContent': {
templateUrl: "templates/form.html",
controller: 'formCtrl'
}
}
})
Run Code Online (Sandbox Code Playgroud)
如需进一步阅读,请访问http://ionicframework.com/docs/api/directive/ionNavView/
jcz*_*lew 49
跟进AlexMart的答案和链接,这样的工作:
.controller('MyCtrl', function($scope) {
$scope.$on('$ionicView.enter', function() {
// Code you want executed every time view is opened
console.log('Opened!')
})
})
Run Code Online (Sandbox Code Playgroud)
Man*_*kla 45
如果已为视图分配了某个控制器,则每次加载视图时都会调用控制器.在这种情况下,您可以在调用控制器后立即执行一些代码,例如:
<ion-nav-view ng-controller="indexController" name="other" ng-init="doSomething()"></ion-nav-view>
Run Code Online (Sandbox Code Playgroud)
在你的控制器中:
app.controller('indexController', function($scope) {
/*
Write some code directly over here without any function,
and it will be executed every time your view loads.
Something like this:
*/
$scope.xyz = 1;
});
Run Code Online (Sandbox Code Playgroud)
编辑:您可能尝试跟踪状态更改,然后在路径更改并访问某个路径时执行一些代码,例如:
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){ ... })
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到更多详细信息:状态更改事件.
为什么不用cache-view ="false"禁用视图缓存?
在您的视图中,将此添加到ion-nav-view,如下所示:
<ion-nav-view name="other" cache-view="false"></ion-nav-view>
Run Code Online (Sandbox Code Playgroud)
或者在你的stateProvider中:
$stateProvider.state('other', {
cache: false,
url : '/other',
templateUrl : 'templates/other/other.html'
})
Run Code Online (Sandbox Code Playgroud)
任何一个都将使您的控制器始终被调用.
比如@Michael Trouw,
你的控制器里面放了这个代码.这将在每次进入或激活状态时运行,您不必担心禁用缓存,这是一种更好的方法.
.controller('exampleCtrl',function($scope){
$scope.$on('$ionicView.enter', function(){
// Any thing you can think of
alert("This function just ran away");
});
})
Run Code Online (Sandbox Code Playgroud)
您可以获得更多灵活性示例,例如$ ionicView.beforeEnter - >,它会在显示视图之前运行.还有更多内容.
| 归档时间: |
|
| 查看次数: |
114354 次 |
| 最近记录: |