Angular.function and OO AngularJS service
Blogs20152015-02-25
OO AngularJS service and Angular.function
Here is an interesting article: Object-oriented AngularJS Services which is similar with my previous blog.The following part is cool which I extracted for reference:
app.factory('AdvancedGithubUser', function($http, SimpleGithubUser) {
var apiUrl = 'https://api.github.com/';
// create new custom object that reuse the original object constructor
var AdvancedGithubUser = function() {
SimpleGithubUser.apply(this, arguments);
};
// reuse the original object prototype
AdvancedGithubUser.prototype = Object.create(SimpleGithubUser.prototype);
// define a new internal private method for this object
function getUserEvents() {
var self = this;
return $http.get(apiUrl + 'users/' + this.username + '/events')
.then(function(response) {
// attach the events API result to our user profile
self.profile.events = response.data;
// promises should always return a result
return response;
});
}
// Now let's override our original getProfile method
AdvancedGithubUser.prototype.getProfile = function() {
var self = this;
// we first call the original getProfile method (aka super method)
var originalGetProfile = SimpleGithubUser.prototype.getProfile.apply(this, arguments);
// we use promises chaining to add additional data
return originalGetProfile.then(function() {
// before returning the result,
// call our new private method and bind "this" to "self"
// we need to do this because the method is not part of the prototype
return getUserEvents.call(self);
});
};
return AdvancedGithubUser;
});self-defined angular.function
Since AngularJS is an object, it can extend itself by adding more static/prototype methods. Like the following:
angular.isValue = function(val) {
return !(val === null || !angular.isDefined(val) || (angular.isNumber(val) && !isFinite(val)));
};
angular.isUndefinedOrNull = function(val) {
return angular.isUndefined(val) || val === null
}This is pretty cool, used with angular.extend to reuse common variables and methods.
