angularjs controller instantiation, ui-router

北战南征 提交于 2020-01-02 22:13:44

问题


When do controllers get instantiated? Is it the first time you visit that state? also, What happens when you revisit the state, does a new controller get instantiated again?

Assume that I have two states, A and B, and I put an alert statement at the top of state B. I noticed that if go from state A to B state B's alert statement sets off which tells me that the controller got instantiated. But suppose I go from state A to B to C and back to B, the alert statement does NOT go off. However, if I go from state A to B to C to B to A to B the alert statement goes off again.

Here is a part of my routes:

state A = app.login

state B = app.pincodeCreate

state C = app.messagelist

.run ($ionicPlatform, startup) ->
  $ionicPlatform.ready(startup.ionicReady)

.config (googleAnalyticsCordovaProvider, $stateProvider, $urlRouterProvider) ->

  $stateProvider

    .state('app', {
      url: '/app',
      abstract: true,
      templateUrl: 'templates/menu.html',
      controller: 'AppController'
    })

    .state('app.pincodeCreate', {
      url: '/pincode',
      views: {
        menuContent: {
          templateUrl: 'templates/pincode.html',
          controller: 'PincodeController'
        }
      }
    })

    .state('app.login', {
      url: '/login',
      views: {
        menuContent: {
          templateUrl: 'templates/login.html',
          controller: 'LoginController'
        }
     }
   })
   .state('app.messagelist', {
      url: '/messagelist',
        views: {
          menuContent: {
            templateUrl: 'templates/messagelist.html',
            controller: 'MessageListController',
            resolve: {
              activities: (utils, store, $state) ->
                utils.getActivities().then ((activities) ->
                  store.isUserLoggedIn(true)
                 activities
              ), (error) ->
              $state.reload()
           }
        }
      }
    })

回答1:


The view's controller for a particular state runs when you go from state outside of the hierarchy tree of that state to that state or one of its descendants.

In other words, if, say, you have the following hierarchy:

     A     B
    /     /
   AA    C
        / \
       C1 C2

Then, switching from A to B would instantiate B. Switching then to C (or C1 or C2, for that matter), and then back to B, would not re-instantiate B's controller.

If you switch to A (or AA), then A would instantiate. Then switching back to B would re-instantiate B.

So, most likely in your case, C is a child state of B. And A and B are in separate ancestry trees.



来源:https://stackoverflow.com/questions/29112489/angularjs-controller-instantiation-ui-router

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