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