javascript - Angular: Is sharing a Controller between views a sign that Service is needed? -
i'm building angular app includes 3 (potential) initial views users not signed in:
intro.html
: gives user option 'sign in' or 'register'register.html
: new user registration formlogin.html
: existing user login form
i have 1 service, auth.service.js
connects firebase:
angular .module('app') .factory('authservice', authservice); authservice.$inject = ['$firebaseauth']; function authservice($firebaseauth) { var ref = new firebase('https://[my-firebase].firebaseio.com'); return $firebaseauth(ref); }
i have 1 controller, login.controller.js
, depends on authservice
create user accounts, login users, connect facebook, etc. here portion of controller:
angular .module('app') .controller('registercontroller', registercontroller); registercontroller.$inject = ['authservice','$location']; function registercontroller(authservice,$location) { var vm = this; vm.createuser = function() { vm.mismatch = false; if (vm.password === vm.confirm) { authservice.$createuser({ email: vm.email, password: vm.password }).then(function(userdata) { $location.path('/people'); }).catch(function(error) { alert(error); }); } else { vm.mismatch = true; vm.mismatchmessage = 'password , confirmation must match'; } }; // login facebook vm.connectfacebook = function() { authservice.$authwithoauthpopup("facebook").then(function(authdata) { $location.path('/places'); }).catch(function(error) { alert("authentication failed:", error); }); }; ... }
i share controller between 3 'intro/register/login' views, feels 'wrong' me. moving createuser
, connectfacebook
, , similar logic auth.service.js
file , creating 'skinnier' controllers each view depend on authservice
better way handle this?
from dev guide (https://docs.angularjs.org/guide/controller):
using controllers correctly
in general, controller shouldn't try much. should contain business logic needed single view.
the common way keep controllers slim encapsulating work doesn't belong controllers services , using these services in controllers via dependency injection. discussed in dependency injection services sections of guide.
so, short answer is, go ahead , split them different controllers. if need share data between them, should use service so.
Comments
Post a Comment