学生开发人员以及我的头在这里,就该既角和更先进的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函数?
它看起来对我来说,要创建一个特定实例的公司类。如果有多个并发用户,并且您使用服务通过使用服务来创建该类的多个实例。是不是有可能有多个用户(或者甚至是不同控制器下的同一用户)在假设他们正在使用相同继承工作在同一个对象上的情况下运行,而事实上他们是单独的对象,这可能会在稍后导致问题? –