在UI路由器状态更改时更新父作用域

时间:2016-03-26 12:49:18

标签: javascript angularjs angular-ui-router

当使用UI路由器更改状态时,正在添加查询参数。在这种情况下' size'

在父控制器' indexAppCtrl'附加到$ stateParams.size的scope属性不会更新状态更改,但$ stateParams对象会更新。

作为修复,我在$ stateChangeSuccess上添加了一个监听器,但它感觉很乱。有没有更好的方法来确保范围是使用stateParams更改进行更新?

app.js

var indexApp = angular.module('indexApp', ['ui.router']);

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

$urlRouterProvider.otherwise('/home');

$stateProvider
    .state('wizard', {
        url: '/wizard?size',
        templateUrl: 'wizard/wizard.html',
        params: {
            size: 'large'
        }
    })

 });

indexAppCtrl.js

    var indexApp = angular.module('indexApp');

    indexApp.controller('indexAppCtrl', ['$scope', '$stateParams', function($scope, $stateParams) {
        $scope.welcome = "welcome to....";

        $scope.stateParams = $stateParams;
        //updates

        $scope.size = $stateParams.size;
        // doesn't update

        $scope.$on('$stateChangeSuccess', function () {
            $scope.size = $stateParams.size;
            //updates
        });

    }]);

的index.html

<html ng-app="indexApp" lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>home</title>
</head>
<body>
    <main ng-controller="indexAppCtrl">

        <button ui-sref="wizard">Start the wizard</button>

        <ui-view>

        </ui-view>
    </main>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

我想说的是,只需将$state.params(状态参数的全局存储)的引用附加到范围变量,该范围变量将在&amp;当$state参数发生任何变化时。

$scope.params = $state.params;

答案 1 :(得分:1)

你的解决方案不是hacky。 $scope.size属性未更新,因为状态更改时不会重新创建控制器。

$stateChangeSuccess是在状态转换完成后更新组件的定义方式,因此您的解决方案是正确的。