Skip to content

Instantly share code, notes, and snippets.

@ewiggin
Last active November 30, 2016 18:25
Show Gist options
  • Select an option

  • Save ewiggin/33d99c37cef1bf050550 to your computer and use it in GitHub Desktop.

Select an option

Save ewiggin/33d99c37cef1bf050550 to your computer and use it in GitHub Desktop.
Dynamic initialization Javascript object - Angular Example
angular.module('service', [])
.factory('Model', function(){
return function Model(item){
this.name = "";
this.surname = "";
this.email = "";
// more attrs
this.constructor = function() {
// init (this) class with valid attr
for (var prop in item) {
// (this) have this prop?
if(this.hasOwnProperty(prop)) {
// yes! Ok... assign value
this[prop] = item[prop];
}
}
};
// init class
this.constructor();
}
});
// in controller have a JSON var named "item"
// and we call the Model dependency
// ...
// $scope.user = new Model(item);
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment