2017-08-29 138 views
3

我描述我的狀態像不刷新的路線變化(UI路由器)角分量

`.state('community.messaging', { 
     template: '<ui-view></ui-view>', 
     url: '/messaging', 
     abstract: true 
    })  
    .state('community.messaging.user', { 
     url: '/user/:userId', 
     component: 'messagingComponent', 
    })` 

,當我使用$ state.go(「community.messaging.user」) 它打開該組件,但在更改另一個狀態或轉到「community.messaging.user」狀態後,它不會清除之前初始化的組件控制器中的先前值。 我的組件是這樣

import messagingController from "./messaging.controller.js"; 
export const messagingComponent = 'messagingComponent'; 
export const messagingComponentOptions = { 
templateUrl: './src/app/components/messaging/messaging.html', 
controller: ['$scope', '$localStorage', '$rootScope', '$transitions', '$timeout', '$cookies', '$state', '$stateParams', 'communityApi', messagingController], 
controllerAs: 'ctrl'} 

和位指示就像

function messagingController($scope, $localStorage, $rootScope, $sanitize, $transitions, $cookies, $state, $stateParams, communityApi) { 
    const self = this; 
    self.currentSelectedChatUser = { 
     id: $stateParams.userId, 
     room: '' 
    }; 
    self.message = ''; 
    self.chatData = []; 
    socket.on('connect', function() { 
     socket.emit('initiate', $stateParams.userId) 
     socket.on('privateRoomCreated', function (data) { 
      if(`self.currentSelectedChatUser.room == ""`) { 
       self.currentSelectedChatUser.room = data.room; 
      } 
     }); 
    )} 
} 

第一次,當我去這種狀態self.currentSelectedChatUser.room == ""但是當我從其他狀態下,再次來到這表明self.currentSelectedChatUser.room == "someroomid"在if語句,但它應該是self.currentSelectedChatUser.room == ""; ,如果重載瀏覽器設置爲self.currentSelectedChatUser.room == ""

回答

0

這是因爲您的控制器在每次更改狀態時都不會重新初始化。您可以使用$ onInit hook初始化您的控制器,每次到達它時,請嘗試:

function messagingController($scope, $localStorage, $rootScope, $sanitize, 
$transitions, $cookies, $state, $stateParams, communityApi) { 
    const self = this; 
    self.$onInit = function() { 
    self.currentSelectedChatUser = { 
      id: $stateParams.userId, 
      room: '' 
    }; 
    }; 
    self.message = ''; 
    self.chatData = []; 
    socket.on('connect', function() { 
    socket.emit('initiate', $stateParams.userId) 
    socket.on('privateRoomCreated', function (data) { 
     if(`self.currentSelectedChatUser.room == ""`) { 
      self.currentSelectedChatUser.room = data.room; 
     } 
    }); 
)} 
}