2015-11-05 48 views
1

我是新來的angularjs,並嘗試使用ui-router作爲搜索頁面。代碼如下Angular-ui-router state.transitionTo無法在控制器功能外工作

<!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> 

我重寫inputonchange並期望$state.transitionTo被稱爲從而哈希標籤將被改變,當用戶輸入的東西和模糊。確實被稱爲transitionTo,但狀態保持不變。

我也嘗試在控制檯中輸入globals.state.transitionTo('home'),但沒有任何反應。

那麼$state在控制器功能之外會變得無效嗎?什麼是正確的方法來做到這一點?

感謝您的幫助。

回答

1

a working example(遵循OP的情況下,搜索領域的損失集中在每一個變化===因爲重定向和狀態再-init發生)

的一種方法,怎麼去$state$stateParams訪問是把它們放在$rootScope

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

而且,爲了使控制器代碼反式提供給我們的觀點,我們必須使用$範圍以及(角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

啓蒙!非常感謝。有一點缺陷是每次按鍵都會使輸入失去焦點。可以通過將參數'{notify:false}'添加到'transitionTo'來解決。 – neuront

0

如果您想使用$狀態外控制器,你可以這樣做:

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