複数のタブに分散された HTML フォーム要素を含むページがあります。ユーザーがフォーム要素に入力したデータを失うことなくタブを切り替えられるようにしたい (また、不必要なデータのリロードを節約したい)。そして、特定のタブへのリンクを誰かに渡すことができるようにしたいと考えています。
ui-extras のスティッキー状態は、私が必要としているものを正確に実行する必要があるようです。私がそれを機能させるのに非常に失敗したことを除いて。
サンプルのソース コードを調べて、サンプルを起動すると、たとえば、controllers.js の 57 行目にある在庫コントローラーのコンストラクターに firebug でブレークポイントを設定すると、コンストラクターが 1 回だけ起動されることがわかります。ただし、コントローラー コンストラクターは何度も起動され、スティッキー状態が存在しない場合とほとんど同じようにアプリケーションが動作しますが、スティッキー状態のデバッグを有効にすると、何かを実行していることがわかります (状態の非アクティブ化と再アクティブ化)。
この回答のコメントで、スティッキー状態は名前付きビューでのみ機能すると述べている人を見つけたので、ビューに名前を付けようとしましたが、違いはありませんでした。
タブの前に明示的な「ルート状態」を挿入してみました。
ng-controller または状態のコントローラー定義によって、コントローラーを挿入しようとしました。
github の例は素晴らしい見せびらかしですが、最小限以上のものであり、実際に何が必要で何が必要でないかを理解するのが難しくなっています。
スティッキー ステートを使い始めるために必要な最小限の例は何ですか? (ボーナス: 私のコードの何が問題なのですか?)。
参考までに、失敗した試行の plunkr をここに示します(以前の試行の選択を確認するには、履歴を参照してください)。
これが私の現在の失敗したソースコードです:
var log = '';
function mkController(msg) {
return function($scope) {
// This is the constructor of a controller
// I'd expect this constructor to the first time a state is loaded.
// When switching to a sister state and back it should not be called again.
if (!$scope.random) {
// I expect the $scope object to be retained when changing states for and
// back. So even if my assumption that the controller will be persistent
// would be wrong this is to check whether the $scope survives.
// If the scope survives the random number will be initialized only once
// and then it won't change anymore:
$scope.random = Math.round(Math.random()*10000);
}
// This log will tell us how often the controller constructor has been called
// (Should be only once, I think)
log += 'creating: ' + msg + '\n';
this.message = log;
}
}
angular.module('plunker', ['ui.router', 'ct.ui.router.extras.sticky', 'ct.ui.router.extras.dsr'])
.controller('ControllerA', mkController('ControllerA'))
.controller('ControllerB', mkController('ControllerB'))
.run(function($templateCache) {
$templateCache.put('root.html', '<div ui-view="myview"></div>');
$templateCache.put('templateA.html', '<div ng-controller="ControllerA as controller"><pre>Random: {{random}}, Message (templateA): {{controller.message}}</pre></div>');
$templateCache.put('templateB.html', '<div ng-controller="ControllerB as controller"><pre>Random: {{random}}, Message (templateB): {{controller.message}}</pre></div>');
})
.config(function($stateProvider) {
$stateProvider
.state('root', {
url: '/',
templateUrl: 'root.html'
}).state('root.stateA', {
url: '/stateA',
views: {
myview: {
templateUrl: 'templateA.html',
}
},
sticky: true,
deepStateRedirect: true
}).state('root.stateB', {
url: '/stateB',
views: {
myview: {
templateUrl: 'templateB.html',
}
},
sticky: true,
deepStateRedirect: true
});
})
.config(function($stickyStateProvider) {
$stickyStateProvider.enableDebug(true);
});