Inherit from rootScope or parent Scope using Controller As syntax


#1

i have 2 controllers Login and Register using Controller As syntax like this

(function(app){

function Register(){ 

}

angular.extend(Register.prototype, {
     isValid: true,
     errors: {},
     setError: function(field, condition){
            var errors = this.errors;
            if (!errors[field]) errors[field] = {};
		errors[field][condition] = true;
		this.isValid = false;
     },
     validationInputs: function(){
              if(this.name.length == 0) this.setError("name", "required");
             return !this.isValid;
     }
});
 app.controller("registerCtrl", [Register]);
})(angular.module("app.controllers"));

(function(app){

function Login(){ 

}

angular.extend(Login.prototype, {
     isValid: true,
     errors: {},
     setError: function(field, condition){
            var errors = this.errors;
            if (!errors[field]) errors[field] = {};
		errors[field][condition] = true;
		this.isValid = false;
     },
     validationInputs: function(){
              if(this.name.length == 0) this.setError("name", "required");
             return !this.isValid;
     }
});
 app.controller("loginCtrl", [Login]);
})(angular.module("app.controllers"));

I want to put setError method to rootScope for Login and Register controller inherit from it, Do i need to write rootScope controller using Controller Syntax ? How do i implement it ?


#2

why dont you just put the errorMessage on the scope? of the controllers… why do you feel the need to create a separate method for that?


#3

i use Controller As syntax because it do not rely on scope. It is easier for Unit Test with controller like plan old javascript object POJO without concerning about angular and scope. In addition, you can easily reuse methods .


#4

I see a fair bit of code duplication in both controllers. Why don’t you create an “Account management” controller that merges this functionality into one?

If you Google for “controller inheritance angular”, a few solutions come up. But I don’t feel like the concept of base classes and inheritance translates very well to Angular.


#5

i used the term $scope loosely but basically I think you are over architecting here… I would agree though that maybe just creating one controller as @fjansen has suggested


#6

thanks @fjansen , but i think the best solution that i create a userService or accountService to store those common methods and properties. I