Angular ui-router loading view twice

痞子三分冷 提交于 2019-12-11 03:33:00

问题


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.'
    }) 

});

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.


回答1:


These are nested views. The reason why there are two messages in your console after reload is: When you start at /home, the home state is loaded. When you go to /home/list over there, only home.list need to be loaded since the home state is already loaded. When you reload there are two states that need to be loaded: home and home.list.

Edit: i dont have enough reputation so i cant comment. 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




回答2:


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

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



来源:https://stackoverflow.com/questions/27621736/angular-ui-router-loading-view-twice

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