Last active
November 30, 2016 18:25
-
-
Save ewiggin/33d99c37cef1bf050550 to your computer and use it in GitHub Desktop.
Dynamic initialization Javascript object - Angular Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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