我正在构建一个 Angular 应用程序,其中包含针对当前未登录的用户的三个(潜在)初始 View :
intro.html
:为用户提供“登录”或“注册”选项register.html
:新用户注册表login.html
:现有用户登录表单
我目前有一项服务 auth.service.js
连接到 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);
}
然后,我有一个 Controller login.controller.js
,它依赖于 authService
来创建用户帐户、登录用户、连接到 Facebook 等。这是一个该 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 and confirmation must match';
}
};
// login with Facebook
vm.connectFacebook = function() {
authService.$authWithOAuthPopup("facebook").then(function(authData) {
$location.path('/places');
}).catch(function(error) {
alert("Authentication failed:", error);
});
};
...
}
我在三个“介绍/注册/登录” View 之间共享此 Controller ,但这对我来说感觉“错误”。将我的 createUser
、connectFacebook
和类似的逻辑移动到我的 auth.service.js
文件中,然后为每个 View 创建“更精简”的 Controller 依赖 authService 是处理此问题的更好方法吗?
最佳答案
来自他们的开发指南( https://docs.angularjs.org/guide/controller ):
Using Controllers Correctly
In general, a Controller shouldn't try to do too much. It should contain only the business logic needed for a single view.
The most common way to keep Controllers slim is by encapsulating work that doesn't belong to controllers into services and then using these services in Controllers via dependency injection. This is discussed in the Dependency Injection Services sections of this guide.
所以,简短的答案是,继续将它们分成不同的 Controller 。如果您需要在它们之间共享数据,您应该使用服务来执行此操作。
关于javascript - Angular : Is sharing a Controller between views a sign that Service is needed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29632298/