私は本当にAngularが好きですが、私はuber n00bであり、まだコンセプトの周りを頭で覆そうとしています。
現在、私はほぼ同じコードを持っている〜9または10のコントローラについて持っている:
$scope.saveForm = function (viewModel) {
if ($scope.id && $scope.id > 0) {
$http.put(appConstants.baseUrl + 'v1/SiteGroupStagings/' + $scope.id, viewModel.data)
.then(function successCallback() {
$scope.master = angular.copy(viewModel);
Notification.success('Success');
}, function errorCallback(response) {
Notification.error('An error occurred while trying to save.<br /><br />' + response.statusText + '<br /><br />'+ response.data);
});
} else {
$http.post(appConstants.baseUrl + 'v1/SiteGroupStagings', viewModel.data)
.then(function successCallback() {
$scope.master = angular.copy(viewModel);
Notification.success('Success');
}, function errorCallback(response) {
Notification.error('An error occurred while trying to save.<br /><br />' + response.statusText + '<br /><br />'+ response.data);
});
}
};
ので、コードの重複は、2つの場所で発生している:
- この全体の方法は、私の多くに重複しています(/
$http.put
の後の)then
機能は正確な重複である
私の質問は、このロジックを集中化してコントローラ間で共有するための推奨方法は何ですか?
これは、私のコントローラの多くでほぼ重複しているコードの単なる一例に過ぎず、明らかにこれは大きな保守性の問題を引き起こすでしょう。
は、URLは、条件付きでそれを設定することができますので、文字列であり、そして、あなたの$http
要求のためにそれを使用して、あなたに
短い答えは、コントローラ間でデータやメソッドを共有するサービスを使用しています – charlietfl