我在Angular向导式webapp上有一些导航按钮。出于美观原因,需要从每个部分删除它们并添加到根" index.html":
<!-- Global navigation buttons for all partials -->
<div class="navbar navbar-fixed-top">
<button class="btn btn-default" back-action>Back</button>
<button class="btn btn-default" next-action>Next</button>
</div>
<div class="container ng-view ng-cloak">
<!-- Partials rendered in here, managed by $routeProvider-->
</div>
我尝试使用指令和范围变量来隔离此逻辑,以绑定click事件并为每个部分应用目标目标:
.directive('nextAction', ['$location', function($location) {
return {
restrict: 'A',
link: function(scope, elm) {
elm.on('click', function () {
var nextUrl = scope.nextUrl;
$location.url(nextUrl);
});
}
};
}])
然后在每个控制器中定义URL:
.controller('FirstStepCtrl', ['$scope', function ($scope) {
$scope.backUrl = '/';
$scope.nextUrl = '/first/second';
...
问题是scope.nextUrl
未定义,因为指令范围不继承控制器范围。
除了它目前还没有工作的事实外,这种方法对我来说似乎有点脆弱,因为它依赖于嵌入在控制器代码中的导航逻辑。
如何创建更好的全局后退/下一个按钮,根据当前&#34;页面&#34;动态重定向?
答案 0 :(得分:1)
使用状态管理器处理后端和后续URL。减轻控制员的责任。然后将其注入处理后退和下一个按钮的指令中。
.factory('stateMgr', ['$rootScope', function ($rootScope) {
var stateMgr = {
backUrl: '',
nextUrl: ''
};
$rootScope.$on('$routeChangeSuccess', function (nextRoute, lastRoute) {
// logic in here will look at nextRoute and then set back and next urls
// based on new route
// e.g. stateMgr.backUrl = '/'; stateMgr.nextUrl = '/whatever';
});
return stateMgr;
}]);
然后
.controller('FirstStepCtrl', ['$scope', function ($scope) {
// do not need to do anything with back/next urls in here
...
和
.directive('nextAction', ['$location', 'stateMgr', function($location, stateMgr) {
return {
restrict: 'A',
link: function(scope, elm) {
elm.on('click', function () {
$location.url(stateMgr.nextUrl);
});
}
};
}])