Angularjsのグローバルバック/次のボタン
-
20-12-2019 - |
質問
角度ウィザードスタイルのWebAppにいくつかのナビゲーションボタンがあります。化粧品の理由から、それらは各部分から削除され、root "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>
.
このロジックをディレクティブおよびスコープ変数を使用して分離しようと、クリックイベントをバインドし、各部分のターゲット宛先を適用しようとしました:
.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
が未定義であることです。
現在それが働いていないという事実と共に、このアプローチはまた、コントローラコードに埋め込まれたナビゲーションロジックに依存しているので、私には少し壊れやすいようです。
現在の「ページ」に基づいて動的にリダイレクトされるより良いグローバルバック/次のボタンを作成する方法は?
解決
State Managerを使用して、後ろと次の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);
});
}
};
}])
. 所属していません StackOverflow