學生開發人員以及我的頭在這裏,就該既角和更先進的JavaScript共享模型中使用的服務
我試圖提高基本角應用程序,並需要共享控制器之間的模型(所以我可以選擇列表中的項目(數組中的JSON對象)以顯示來自同一對象的更多數據)。
服務:
(function() {
'use strict';
angular
.module('App')
.factory('companiesService', ['$http', 'ngAuthSettings', companiesService]);
function companiesService($http, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
var Companies = function() {
this.records = [];
this.loading = false;
this.params = {};
this.params.filter = this.filter;
this.params.offset = 0;
this.params.max = 10;
};
Companies.prototype = {
loadData : function() {
if (this.loading || this.error || this.end) return;
this.loading = true;
$http({
method : 'POST',
url : serviceBase + 'company.php',
data : $.param(this.params),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).then(function(response) {
for (var i = 0, len = response.data.records.length; i < len; i++) {
this.records.push(response.data.records[i]);
}
this.error = response.data.error;
this.message = response.data.message;
this.params.offset = parseInt(response.data.offset) + this.params.max;
this.end = len < this.params.max;
this.loading = false;
}.bind(this));
},
getCompany : function(id) {
var recs = this.records;
if (recs) {
for (var i = 0, len = recs.length; i < len; i++) {
if (recs[i].id == id) {
return recs[i];
} else {
return -1;
}
}
}
}
};
return Companies;
}
})();
控制器(用於列表視圖) - 這工作得很好
(function() {
'use strict';
angular
.module('App')
.controller('companyController', ['$scope', 'companiesService', companyController]);
function companyController($scope, companiesService) {
$scope.companies = new companiesService();
}
})();
第二控制器如何可以訪問相同的數據,即的記錄屬性返回'公司' - 或者更具體地說,我如何在第二個控制器中的這些記錄上的服務中調用getCompany函數?
它看起來對我來說,要創建一個特定實例的公司類。如果有多個併發用戶,並且您使用服務通過使用服務來創建該類的多個實例。是不是有可能有多個用戶(或者甚至是不同控制器下的同一用戶)在假設他們正在使用相同繼承工作在同一個對象上的情況下運行,而事實上他們是單獨的對象,這可能會在稍後導致問題? –