我現在的控制器都充滿了隱藏的提交按鈕邏輯,並經過後端獲取的數據顯示成功消息:AngularJS - 如何在多個控制器中共享監視對象?
angular.module('testApp').controller('TestCtrl', ['$scope', 'testService',
function ($scope, testService) {
$scope.loading = false;
$scope.updated = false;
$scope.error = false;
$scope.submit = function() {
if(!$scope.form.$valid) {
return;
}
$scope.loading = true;
testService.doBackendUpdate({some:'data'})
.success(function() {
$scope.error = $scope.loading = false;
$scope.updated = true;
})
.error(function(error) {
$scope.updated = $scope.loading = false;
$scope.error = true;
});
};
}]);
和HTML:
<alert type="'success'" close="updated = false" ng-show="updated">Data Updated!</alert>
<button ng-hide="loading">update</button>
什麼,我想有這些,而不是變量是某種對象,並再次使用 其他控制:
angular.module('testApp').controller('TestCtrl', ['$scope', 'testService',
function ($scope, testService) {
$scope.status = new ActionStatus();
$scope.submit = function() {
if(!$scope.form.$valid) {
return;
}
$scope.status.loading();
testService.doBackendUpdate({some:'data'})
.success(function() {
$scope.status.succes();
})
.error(function(error) {
$scope.status.error();
});
};
}]);
和HTML:
<alert type="'success'" close="updated = false" ng-show="status.isUpdated">Data Updated!</alert>
<button ng-hide="statuss.isLoading">update</button>
但我怎麼能做到這一點? AngularJS手錶在觀察變量時丟失了上下文,所以我不能通過原型創建一個ActionStatus對象。
任何想法?
它解壓到[**服務**](http://docs.angularjs.org/guide/services)?例如'.controller('TestCtrl',['$ scope','testService','ActionStatus',function($ scope,testService,ActionStatus){$ scope.status = ActionStatus; ...' –
但是服務是單身人士。如果我在同一頁面上有兩個控制器...? – gerasalus