javascript - Angular : Is sharing a Controller between views a sign that Service is needed?

标签 javascript angularjs

我正在构建一个 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 ,但这对我来说感觉“错误”。将我的 createUserconnectFacebook 和类似的逻辑移动到我的 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/

相关文章:

angularjs - 设置 Angular-UI Select2 多重指令的初始值

javascript - 一段时间后 Canvas 开始滞后

javascript - Angularjs ui-router 与 Materialise-Angular 问题

javascript - 未捕获的类型错误 : Cannot read property 'attributes' of undefined

javascript - AJAX URL 中的十进制值

javascript - ng-repeat 中的 AngularJS 指令范围绑定(bind)问题

angularjs - 如何摧毁未兑现的 promise

javascript - 从 UIWebView Javascript 监听 Objective-C 中的通知

javascript - Javascript 的媒体查询方法

javascript - 谷歌地图javascript禁用谷歌标志链接