簡體   English   中英

狀態更改時將數據傳遞到Angular UI Router不變

[英]Pass data to Angular UI Router not changing when state change

我想在使用angular-ui-router時將不同的數據傳遞給每個狀態。 盡管能夠傳遞數據,但路由更改時它不會更改。 例如,請參見下面的代碼:

.config(function($stateProvider, $urlRouterProvider) {


    $stateProvider

        // route to show main page with satisfied/unsatisfied
        .state('main', {
            url: '/main',
            templateUrl: 'container.html',
            controller: 'formController',

        })

        .state('main.happy', {
            url: '/happy',
            data: {  happy: true },  
            templateUrl: 'happy.html',

        })

        .state('main.sad', {
            url: '/sad',
            data: {  happy: false },  
            templateUrl: 'welcome.html'
        })


    // catch all route
    $urlRouterProvider.otherwise('/main');


})

在上面的代碼中,當我轉到路徑/happy ,可以看到正在使用數據,但是當我轉到路徑/sad ,數據沒有更改。 盡管在路徑/sad的情況下happy的值必須為false,但在其他情況下仍然保留。 僅當我刷新數據時才更改。 使用我的Angular不能達到全部目的。

您可能需要執行以下操作:

.state('main', {
    url: '/main/:mood',
    templateUrl: 'container.html',
    controller: 'formController',
})

mainApp.controller('formController', function($state) {
    console.log($state.params.mood); // -> happy
});

之所以這樣工作是因為您在此處使用了子狀態( main.happymain.sad )。

當您在子狀態之間移動時,ui-router不會創建父控制器的新實例(在您的情況下為formController )。 如果您願意,可以在formController添加簡單的console.log ,然后查看該消息僅顯示一次。

您要做的就是每次進入狀態時都創建一個新的formController實例。

如果要刷新子視圖/父視圖,可以直接使用$state服務並通過參數reload等於true的options對象傳遞來完成。

$state.go('main.happy', null, {reload: true});

或在您的視圖中的某處使用ui-sref-opts指令,例如:

<a ui-sref="main.happy" ui-sref-opts="{reload: true}">Go to happy state</a>

我還通過工作演示為您創建了插件: http ://plnkr.co/edit/GxNLWsvlLotRRNdjUxFr?p=preview

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM