AngularJS + OOP is an exciting feature to explore
Greetings! I have been successfully incorporating OOP with AngularJs for some time now. I initially delved into this realm by seeking guidance on angularjs with oop inheritance in action. This approach allows you to define your classes as angular services, which can be extended or inherited from as follows:
Application.factory('AbstractObject', [function () {
var AbstractObject = Class.extend({
virtualMethod: function() {
alert("Hello world");
},
abstractMethod: function() {
throw new Error("Pure abstract call");
}
});
return AbstractObject;
}]);
Application.factory('DerivedObject', ['AbstractObject', function (AbstractObject) {
var DerivedObject = AbstractObject.extend({
virtualMethod: function() {
alert("Hey!");
this._super();
},
abstractMethod: function() {
alert("Now I'm not abstract");
}
});
return DerivedObject;
}]);
Plunker: http://plnkr.co/edit/rAtVGAsNYggBhNADMeoT
Implementing this method allows for the seamless integration of classes into Angular's infrastructure, leveraging features from both the OOP and AngularJs worlds. Dependency injection becomes effortless, simplifying class structure and enabling the reuse of boilerplate controller code.
Nevertheless
Despite its advantages, there are limitations to this approach when it comes to recursive class definitions like the scenario involving classes Blog
and Tag
.
Application.factory('Blog', ['Tag', function (Tag) {
var Blog = Class.extend({
tags: function() {
return this.tags;
}
});
return Blog;
}]);
Application.factory('Tag', ['Blog', function (Blog) {
var Tag = Class.extend({
Blogs: function() {
return this.blogs;
}
});
return Tag;
}]);
Unfortunately, this will not work due to circular dependencies within Blog
and Tag
.
P.S
I discovered a somewhat convoluted solution that temporarily resolved my issue but proved to be inefficient in the long run:
Application.factory('BlogNamespace', [function () {
var Blog = Class.extend({
tags: function() {
return this.tags;
}
});
var Tag = Class.extend({
Blogs: function() {
return this.blogs;
}
});
return {
Tag: Tag,
Blog: Blog
};
}]);
Question
The workaround provided above falls short as namespaces can also be affected by circular dependencies, raising another layer of complexity. Are there any recommendations for addressing this issue more effectively in a general context?