javascript 在 Angular 中有主控制器好吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20433568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:28:42  来源:igfitidea点击:

Is it good to have main controller in Angular?

javascriptangularjs

提问by dinodsaurus

I dont know if this is a good practice... I have a controller defined in route config but because my HomeCtrlis in ng-ifstatement he cannot listen for loginSuccessso I made MainCtrlwhich listens for loginSuccessand reacts appropriately. This code works just fine but this smells like a hack to me. Should I remove MainCtrland make it a service? If so some example would be really great.

我不知道这是否是一个好习惯......我在路由配置中定义了一个控制器,但是因为我HomeCtrlng-if声明他无法监听loginSuccess所以我做了MainCtrl哪个监听loginSuccess并做出适当的反应。这段代码工作得很好,但这对我来说就像一个黑客。我应该删除MainCtrl并使其成为一项服务吗?如果是这样的话,一些例子会非常棒。

Index.html

索引.html

<body ng-app="myApp" ng-controller="MainCtrl">
    <div ng-if="!isLoged()">
      <signIn></signIn>
    </div>
    <div ng-if="isLoged()">
      <div class="header">
          <div class="nav">
            <ul>
                <a href="/"><li class="book">navItem</li></a>
            </ul>
          </div>
      </div>
      <div class="container" ng-view=""></div>
    </div>
</body>

App.js

应用程序.js

    angular.module('myApp', [])
      .config(function ($routeProvider) {
        $routeProvider
          .when('/', {
            templateUrl: 'views/main.html',
            controller: 'HomeCtrl'
          })
          .otherwise({
            redirectTo: '/'
          });
      })
  .controller('MainCtrl', function ($scope) {
    $scope.user = false;
    $scope.isLoged = function(){
         if($scope.user){
          return true;
         }else{
          return false;
         }
    }
    $scope.$on('event:loginSuccess', function(ev, user) {
       $scope.user = user;
       $scope.$apply();
    });
  })
  .controller('HomeCtrl', function ($scope, $location) {
  //this is home controller  
  })
  .directive('signIn', function () {
    return {
      restrict: 'E',
      link: function (scope, element, attrs) {
        //go to the server and then call signinCallback();
      }
    };
  })
  .run(['$window','$rootScope','$log',function($window, $rootScope){
    $window.signinCallback = function (res) {
      if(res){
        $rootScope.$broadcast('event:loginSuccess', res);
      }
      else{
        $rootScope.$broadcast('loginFailure',res);
      }
    }; 
  }]);

采纳答案by m59

I start all of my Angular projects with:

我开始我所有的 Angular 项目:

<html ng-app="appName" ng-controller="appNameCtrl">

<html ng-app="appName" ng-controller="appNameCtrl">

The use of a "global" controller may not be necessary, but it is always nice to have it around when a need arises. For example, I use it in my CMS to set a binding that initiates the loading of everything else - so all the sub controllers are loaded because of it. That isn't violating separation of concerns because the global controller's concern IS to facilitate the loading of other controllers.

使用“全局”控制器可能不是必需的,但在需要时使用它总是很好的。例如,我在我的 CMS 中使用它来设置一个绑定来启动其他所有内容的加载 - 因此所有子控制器都因此被加载。这并不违反关注点分离,因为全局控制器的关注点是为了促进其他控制器的加载。

That said, just be sure to keep things as modular/separated and reusable as possible. If your controllers rely on the global controller's existence in order to function, then there is an issue.

也就是说,一定要尽可能保持模块化/分离和可重用。如果您的控制器依赖于全局控制器的存在才能运行,那么就会出现问题。

回答by krosullivan

In my opinion angular js' power comes with separating out clearly the different controllers directives, services, resources etc. Ideally controllers are linked to templates or partials and are used to update the front end and make calls to services or resources. The sooner you start making these separations the sooner you will start making clean and scalable apps that other developers can quickly make sense of. For app structure I would highly recommend you look into either of these two tools:

在我看来,angular js 的强大之处在于可以清楚地分离出不同的控制器指令、服务、资源等。理想情况下,控制器链接到模板或部分,用于更新前端并调用服务或资源。您越早开始进行这些分离,您就会越早开始制作其他开发人员可以快速理解的干净且可扩展的应用程序。对于应用程序结构,我强烈建议您查看以下两个工具中的任何一个:

Lineman.js

线人.js

and

Yeomann

约曼

The lineman site actually has a really good round up of how the two differ, if you scroll down.

如果向下滚动,lineman 站点实际上对两者的区别进行了非常好的总结。

In your scenario there are many ways to link controllers or make function calls that are in different scopes. You can either create a service that injects to your controllers or you can use $emit and $on to set up notifications in the app eg:

在您的场景中,有多种方法可以链接控制器或进行不同范围内的函数调用。您可以创建一个注入控制器的服务,也可以使用 $emit 和 $on 在应用程序中设置通知,例如:

In controller A

在控制器 A

$rootScope.$on('myNotifier:call', function() {
        myFunction();
    });

And in Controller B or any other controller you could call myFunction() with:

在控制器 B 或任何其他控制器中,您可以使用以下命令调用 myFunction():

$scope.$emit('newPatientModal:close');