角UI路由器加载视图两倍 [英] Angular ui-router loading view twice
问题描述
我用我的角角的应用程序UI的路由器。对于路由部分,我已经写了
I'm using angular ui-router in my angular application. For the routing part I've written
var routerApp = angular.module('routerApp', ['ui.router']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
templateUrl: 'partial-home.html',
controller : function($scope,$state){
$scope.$on('$viewContentLoaded', function(){
console.log("home content loaded",$state.current);
})
}
})
// nested list with custom controller
.state('home.list', {
url: '/list',
template: 'I am using a list.'
})
// nested list with just some random string data
.state('home.paragraph', {
url: '/paragraph',
template: 'I could sure use a drink right now.'
})
});
在局部home.html做为我wriiten: -
In partial-home.html I've wriiten:-
<div class="jumbotron text-center">
<h1>The Homey Page</h1>
<p>This page demonstrates <span class="text-danger">nested</span> views.</p>
<a ui-sref=".list" class="btn btn-primary">List</a>
<a ui-sref=".paragraph" class="btn btn-danger">Paragraph</a>
</div>
<div ui-view></div>
现在,当我执行这个程序在浏览器中,如果我开的路线
Now when I'm executing this app in browser, if I open the the route
/home
浏览器控制台显示出家庭内容加载一次,然后如果我点击列表中的链接,地址栏变为
The browser console is showing "home content loaded" once, and then if I click on the list link, the addressbar changes to
/home/list
然后还控制台显示一次。
And then also the console is shown once.
但是,如果我刷新浏览器选项卡在那个时候(当路线是家庭/列表),控制台显示的两倍。请帮我,为什么这件事情发生了。
But if I refresh the browser tab at that time (when the route is home/list), the console is shown twice. Please help me why this thing happening.
推荐答案
由于home.list一种家的孩子的状态,当你重新加载页面home.list
它首先初始化视图家居控制器比查看列表控制器,所以$ viewContentLoaded被调用两次
because home.list is a child state of home and when you reload page for home.list it first initializes view of home controller than view of list controller so $viewContentLoaded is called twice
我猜你使用这会导致孩子和家长共享相同的范围家里模板中的UI视图。 u的聆听双方的孩子和家长的范围事件。所以很自然地被调用两次
i guess that you use ui-view inside home template which causes child and parent to share the same scope. u are listening to both child's and parent's scope for the event. so it is natural to be called twice
这篇关于角UI路由器加载视图两倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!