我是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
的input
,并期望调用$state.transitionTo
,因此当用户输入某些内容并模糊时,哈希标记将被更改。确实调用了transitionTo
,但是状态保持不变。我也尝试在控制台中键入
globals.state.transitionTo('home')
,但没有任何反应。那么
$state
是否在控制器功能之外变为无效?正确的方法是什么?谢谢你的帮助。
最佳答案
有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
关于javascript - Angular-ui-router state.transition在 Controller 功能外部不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33542360/