【问题标题】:How to set $stateParams based on variable in controller?如何根据控制器中的变量设置 $stateParams?
【发布时间】:2017-08-20 10:25:02
【问题描述】:

我想根据 $state 更改socket.io 连接,所以当用户更改状态时,我想将$stateParams 分配给searchEnv,这样我们就可以使socket 连接处于活动状态并开始接收该环境的消息。假设我有 $state app.dit 我想将 envId 设置为 dit。 我如何使用 angular $stateProvider 来完成这项任务?

尝试为 $States 实现一个视图和控制器,而不是多个。

Ctrl.js

var searchEnv = $stateParams.envId;

socket.on(searchEnv + 'Consumer', function(data) {
    $scope.event.push(data);
});

app.js

.state('app.dit', {
    url: '/dit/:envId',
    templateUrl: 'view/partials/dit.html',
    controller: 'DitCtrl'
})
.state('app.st', {
    url: '/st/:envId',
    templateUrl: 'view/partials/dit.html',
    controller: 'DitCtrl'
})

mainCtrl.js

$scope.tabs = [{
        heading: 'Home',
        route: 'app.home',
        active: true
    },
    {
        heading: 'DIT',
        route: 'app.dit',
        active: false
    },
    {
        heading: 'ST',
        route: 'app.st',
        active: false
    },
    {
        heading: 'UAT',
        route: 'app.uat',
        active: false
    },
    {
        heading: 'LSP',
        route: 'app.lsp',
        active: false
    }
];

【问题讨论】:

    标签: javascript angularjs sockets


    【解决方案1】:

    使用$state.includes 方法:

    //EXAMPLES
    
    $state.$current.name = 'contacts.details.item';
    
    // Using partial names
    $state.includes("contacts"); // returns true
    $state.includes("contacts.details"); // returns true
    $state.includes("contacts.details.item"); // returns true
    $state.includes("contacts.list"); // returns false
    $state.includes("about"); // returns false
    

    欲了解更多信息,请参阅UI-Router $state API Reference - includes method

    【讨论】:

      【解决方案2】:

      您可以在$scope$rootScope 上的controller 上观看$stateChangeStart 上的操作

          $rootScope.$on('$stateChangeStart', 
          function(event, toState, toParams, fromState, fromParams, options){ ... })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多