what im trying to achive is have an Model function that contain all the object behaviour, and a factory singelton that creates, save, update, and keep collections of such models, so that i can use them inside angular controllers.
For example i will use Users Model
Attempt1
Model:
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.user+'');
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;
}
}
Factory:
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));
return container[index-1];
}
});
First question: does angular provide a way to create Models to be injected in services so that i dont have to save them in window.interfaces* ?
now in my controller i can have something like
myApp.controller('ctrl1',function(People,$scope){
$scope.people = people.all();
});
myApp.controller('ctrl2',function(People,$scope){
$scope.people = people.all();
});
<div ng-controller="ctrl1">
<label ng-repeat="person in people">{{person.first_name()}}</label>
<button ng-click="person.change('new name')"></button>
</div>
<div ng-controller="ctrl2">
<label ng-repeat="person in people">{{person.first_name()}}</label>
</div>
using such approach i can contain behaviour of my objects in their own models,yet performance wise, how bad is this approach ? does angular watchers will easily track this or it will trigger un-needed digest cycles ?
Fiddle for example http://ift.tt/1qfFoFN
Aucun commentaire:
Enregistrer un commentaire