对于 AngularJS 中的所有 CRUD 操作,使用单个控制器、服务和视图是否是一个好习惯?

Is it a good practise to have a single controller, service and view for all CRUD operations in AngularJS?

我是 AngularJS 的新手,我正在探索使用 MVC 启动应用程序的最佳实践。我在网上找到的选项是

  1. 每个视图应该有一个控制器,控制器负责视图中的每个动作,所有需要的方法应该在一个服务中

  2. 每个动作应该有一个视图和一个控制器,但所有动作的所有方法都在同一服务中。

让我知道哪一个是最好的。

我还有一个问题。如果我们把所有的增删改查方法放在同一个服务中,如果我们在一个只需要get操作的视图中调用该服务,那么它会增加那个特定视图的负载吗?请帮助我走上正确的道路。

我是一个相当大的项目的联合负责人。

主要有我们遵循的做法... https://github.com/johnpapa/angular-styleguide

关于您的具体问题...

each view should have one controller , the controller is responsible for every action in view and all the methods required should be in a single service

同意这是一个好方法。我们使用 ui-router 来实现这一点,您可以在其中为每个路由定义 URL、模板 HTML 页面和控制器。 但是,我建议您不要严格遵循这种方法。 例如,在所有视图之间共享数据的地方,我们使用 header 包含定义了 header 控制器。 另外,说所有需要的方法都应该在一个服务中是荒谬的。例如,如果您的视图需要向 2 个不同的端点发出请求,那么这些端点很可能被组织成 2 个不同的服务,因此您将同时注入。

重要提示:控制器的代码应该最少。它应该尝试提供视图和服务方法之间的挂钩。

重要提示:使用控制器 As 语法 - 不要在所有地方使用 $scope!这样很容易看出哪个控制器与特定方法相关联

each action should have one view and one controller. but all the methods for all actions in same service.

跟我说话听起来很疯狂!

Apart from this I have another question. If we place all the crud methods in same service, and if we call the service in a view which needs only get operation, then will it increase load on that particular view?.. Please help me in taking the right path

如果您将所有 CRUD 放在同一个服务中并且您只使用 GET 那么显然您是在不必要地注入未使用的方法。 但是,该服务将在内存中,因此如果您将它注入到仅使用 PUT 的其他地方,那么这样做的成本将是最小的。

代码的组织和管理需要一定的开销,如果你懂事,问题不大。

我们倾向于将 since 端点的所有 CRUD 操作组织到单个服务中。

希望对您有所帮助。

header 控制器的示例代码与 ui.router ...

ui.router 配置为 ...

  .state('ou-details', {
    templateUrl: 'routes/ou/details/ou-details.html',
    controller: 'OuDetailsController',
    controllerAs: 'ouDetailsCtrl',
    url: '/ou/details/:id',
    authenticate: true
  })
  .state('ou-edit', {
    templateUrl: 'routes/ou/edit/ou-edit.html',
    controller: 'OuEditController',
    controllerAs: 'ouEditCtrl',
    url: '/ou/edit/:id',
    authenticate: true
  })

等等...

index.html 的 body 看起来像...

<body data-ng-app="admin">
  <header data-ng-include src="'includes/header/header.html'"></header>
  <section data-ui-view="data-ui-view"></section>
  <footer data-ng-include src="'includes/footer/footer.html'"></footer>
</body>

header.html 看起来像...

<div data-ng-controller="HeaderController as headerCtrl">
   <div data-ng-bind="headCtrl.someProperty"/>
</div>

(如果这个标记有点错误,我深表歉意,因为它是用 JADE 编写的,我只是把它扔进了一个可能有点混乱的转换器中)