Angular-ui-router state.transitionTo不在控制器功能外工作

时间:2015-11-05 10:36:07

标签: javascript angularjs angular-ui-router

我是angularjs的新手,并尝试使用ui-router进行搜索页面。代码就像

<!DOCTYPE html>
<html ng-app='test'>
<head>
    <meta charset='utf-8'>
    <script src='angular.min.js'></script>
    <script src='angular-ui-router.min.js'></script>
</head>
<body>
    <nav>
        <a ui-sref='home'>Home</a>
        <a ui-sref='search'>Search</a>
    </nav>
    <div ui-view></div>

脚本

<script>
var globals = {};
var app = angular.module('test', ['ui.router'])
app.config(['$stateProvider', '$urlRouterProvider', function (state, route) {
    route.otherwise('/');
    state.state('home', {
        url: '/',
        template: '<h1>Home</h1>',
        controller: [function () {}]
    }).state('search', {
        url: '/search/:s',
        controller: ['$state', function (state) {
            globals.state = state;
            trans('xyz'); // test, and this is working, when click "Search" first time
        }],
        // want to transition when input changed & blur, but the hash tag remains "xyz"
        template: '<h1>Search</h1><input onchange="trans(this.value)">'
    });
}]);

function trans(x) {
    globals.state.transitionTo('search', {s: x});
    console.log('Transition to', x);
}
</script>

我覆盖onchange的{​​{1}}并期望调用input,因此当用户输入内容并模糊时,哈希标记会发生变化。确实被称为$state.transitionTo,但状态保持不变。

我也尝试在控制台中输入transitionTo,但没有任何反应。

globals.state.transitionTo('home')在控制器功能之外变为无效吗?这样做的正确方法是什么?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

a working example (为了遵循OP方案,搜索字段丢失集中于每次更改===,因为重定向和状态重新初始化发生)

一种方法是,如何访问$state$stateParams是将其置于 $rootScope

app.run(['$rootScope', '$state', '$stateParams',
  function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
}])

并且,为了使控制器代码可用于我们的视图,我们必须使用$ scope(角度1的本质):

.state('search', { 
    url: '/search/:s',
    controller: ['$state', '$scope', '$stateParams', function (state, $scope, $stateParams) {
      $scope.search = $stateParams.s;
        globals.state = state;
        //trans('xyz'); // test, and this is working, when click "Search" first time
        $scope.trans = trans;
    }],
    // want to transition when input changed & blur, but the hash tag remains "xyz"
    templateUrl: 'tpl.html' // used more complex stuff, see plunker
});

检查所有here

答案 1 :(得分:-1)

如果你想使用$ state outside controller,你可以这样做:

angular.element(document.body).injector().get('$state').transitionTo('home');