0
即时尝试存档的模型函数包含所有对象行为,以及创建,保存,更新和保留这些模型集合的工厂单例模式,所以我可以在角度控制器中使用它们。angularjs设计模式和从服务器获取数据的最佳做法
第一个问题:角度提供了一种方法来创建模型,以便在服务中注入,这样我就不必将它们保存在window.interfaces *中?
使用这样的方法我可以在自己的模型中包含我的对象的行为,但性能明智,这种方法有多糟?角度观察者是否会轻松跟踪这一点,否则会触发不需要的摘要循环?
例如 小提琴http://jsfiddle.net/zalabany/j230cuy4/1/
var myApp = angular.module('myApp', []);
myApp.service('People', function() {
var container = [];
var self = this;
this.all = function() {
console.log('called all', container);
return container;
}
this.createMany = function(data) {
data.forEach(function(el) {
container.push(new window.interfaces.Person(el));
});
return container;
}
this.createOne = function(obj) {
var index = container.push(new window.interfaces.Person(obj));
console.log('add one to container', index, container);
return container[index - 1];
}
});
function ctrl2(People, $scope) {
$scope.people = People.all();
};
function ctrl1(People, $scope) {
$scope.people = People.all();
$scope.add = function() {
console.log(People.createOne({
id: 1,
fullname: 'Jhon Doe'
}));
}
};
window.interfaces = window.interfaces || {};
window.interfaces.Person = function(data) {
var self = this;
data = data || {};
//TypeCasting For properties
this.id = parseInt(data.id);
this.saved = !!(this.id);
this.deleted = !!(data.time_deleted > 0);
this.fullname = String(data.fullname + '');
data = undefined; //clear data variable. we dont need it anymore
///Methods
this.first_name = function() {
return self.fullname.substring(0, self.fullname.indexOf(' '));
};
this.last_name = function() {
return self.fullname.substring(self.fullname.lastIndexOf(' '));
}
this.change = function(v) {
self.fullname = (self.fullname === 'hello world') ? 'Was hello' : v;
}
}
div[ng-controller] {
float: left;
width: 200px;
}
label {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="ctrl1">
<h2>
Ctrl1
</h2>
<label ng-repeat="person in people">{{person.first_name()}}</label>
<button ng-click="add();">Click Me to create objects</button>
</div>
<div ng-controller="ctrl2">
<h2>
Ctrl2
</h2>
<label ng-repeat="person in people">
{{person.first_name()}}
<button ng-click="person.change('new name');">Change</button>
</label>
</div>
</div>
所以在给定的例子中,人和人类的正确提供者是什么?将角色服务和人作为角度常量是否是正确的实现? – Zalaboza
我有点困惑,如果你可以解释你的目标与人和人的事情..我的意思是你为什么需要他们两个?一般来说,我们有一个Person服务或一个Person Factory,我们可以通过Person.all或Person.one等函数来调用apis ... – atefth
人会有一些方法,比如在获得逻辑后获取用户名,验证用户准备好被保存在数据库等等 人们是为人的集合,它具有如何从数据库中检索他们的逻辑,如何创建他们, – Zalaboza