最初のアプローチ: ng-click を使用してモデルをサービスに保存し、次に場所に移動する
コントローラーの get 属性を呼び出すリスト項目に ng-click を追加して、href を削除することから始めます。
<nav>
<ul class="list">
<li ng-repeat="product in data | startFrom:currentPage*pageSize | limitTo:pageSize" ng-click="getAttributes(product)">
<span>{{product}}</span>
<a href="">{{product.prd_name}}</a>
</li>
</ul>
</nav>
次に、ルートを単に /getAttributes に再構成します
myApp.config([
'$routeProvider', function($routeProvider) {
$routeProvider
.when('/getAttributes/', {
templateUrl: 'view/attributes.jsp',
controller: 'attributeController'
}).otherwise({
redirectTo: '/mainMenu'
});
}
]);
コントローラーで、前述の ng-click によって呼び出される getAttributes というメソッドを追加します。サービスを呼び出し、その setModel 関数を使用して、クリックされたモデルを保持します。最後に、getAttributes をルーティングします。
myApp.controller('someController', [
'$scope', '$location', 'someService', function($scope, $location, someService) {
$scope.getAttributes = function(model) {
someService.setModel(model);
$location.url('getAttributes');
};
}
]);
属性コントローラーは同じサービスを呼び出し、その getModel メソッドを使用してモデルを設定します。
myApp.controller('attributeController', [
'$scope', 'someService', function($scope, someService) {
$scope.model = someService.getModel();
}
]);
このサービスは、次のようなものを求めています。
myApp.service('someService', function() {
var model;
return {
getModel: function() {
return model;
},
setModel: function(newModel) {
model = newModel;
}
};
});
このアプローチは、他の方法で getAttributes にルーティングしない場合にのみ適しています。より柔軟な 2 番目のアプローチが可能です。
2 番目のアプローチ: Resolve を使用してモデルを取得し、サービスに設定してからコントローラーにロードする
href を ng-href に変更し、getAttribute/123 などにします。
<nav>
<ul class="list">
<li ng-repeat="product in data | startFrom:currentPage*pageSize | limitTo:pageSize">
<span>{{product}}</span>
<a ng-href="/getAttributes/{{product.id}}">{{product.prd_name}}</a>
</li>
</ul>
</nav>
以下に示すように、製品 ID を受け入れるようにルートを変更します。さらに、解決オブジェクトを追加します。このオブジェクトは someService を呼び出し、次にサーバーを呼び出し、製品属性を取得して、モデル変数を結果と等しく設定します。
myApp.config([
'$routeProvider', function($routeProvider) {
$routeProvider
.when('/getAttributes/:id', {
templateUrl: 'view/attributes.jsp',
controller: 'attributeController',
resolve: {
getModel: function(someService) {
return someService.get();
}
}
}).otherwise({
redirectTo: '/mainMenu'
});
}
]);
前述のように、サービスは /getAttributes/id ルートで渡された ID を取得し、それを使用してサーバーを呼び出します。別の方法として、代わりにサービスがこのためのリポジトリを呼び出すようにすることもできます。最終結果は同じです。モデル変数をサーバーへの呼び出しの結果と等しく設定します。
myApp.service('someService', [
'$http', function($http) {
var model;
return {
get: function(id) {
return $http.get('api/attribute/' + id).then(function(response) {
model = response.data;
});
},
getModel: function() {
return model;
},
setModel: function(newModel) {
model = newModel;
}
};
}
]);
最後に、attributeController は最初の例と同じように動作します。$scope.model を someService.getModel() と等しく設定し、それによって製品属性を提供します。
このアプローチの利点は、ルートがアプリのどこからでも問題なくディープ リンクできることです。