Created
August 4, 2017 16:20
-
-
Save edysegura/2a5058dfc05501f7a6365c766f95a20f to your computer and use it in GitHub Desktop.
How to create class in AngularJS
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
.factory('User', function (Organisation) { | |
/** | |
* Constructor, with class name | |
*/ | |
function User(firstName, lastName, role, organisation) { | |
// Public properties, assigned to the instance ('this') | |
this.firstName = firstName; | |
this.lastName = lastName; | |
this.role = role; | |
this.organisation = organisation; | |
} | |
/** | |
* Public method, assigned to prototype | |
*/ | |
User.prototype.getFullName = function () { | |
return this.firstName + ' ' + this.lastName; | |
}; | |
/** | |
* Private property | |
*/ | |
var possibleRoles = ['admin', 'editor', 'guest']; | |
/** | |
* Private function | |
*/ | |
function checkRole(role) { | |
return possibleRoles.indexOf(role) !== -1; | |
} | |
/** | |
* Static property | |
* Using copy to prevent modifications to private property | |
*/ | |
User.possibleRoles = angular.copy(possibleRoles); | |
/** | |
* Static method, assigned to class | |
* Instance ('this') is not available in static context | |
*/ | |
User.build = function (data) { | |
if (!checkRole(data.role)) { | |
return; | |
} | |
return new User( | |
data.first_name, | |
data.last_name, | |
data.role, | |
Organisation.build(data.organisation) // another model | |
); | |
}; | |
/** | |
* Return the constructor function | |
*/ | |
return User; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment