简体   繁体   English

如何链接到Angular中的不同控制器

[英]How to link to different controllers in Angular

I created a ListCtrl , responsible for fetching data from server and paginating it (it will work for ALL my resources). 我创建了一个ListCtrl ,负责从服务器获取数据并对其进行分页(它将适用于我所有的资源)。 However, It must receive a few configurations prior to setup the Path to the resource, default limit, and so on... 但是,在设置资源的路径,默认限制等之前,它必须接受一些configurations

The way I thought doing it, is to use my ListCtrl inside a bigger Controller, but initialising it with a few params like this: 我认为这样做的方式是在更大的Controller中使用ListCtrl,但使用以下一些参数对其进行初始化:

<div ng-controller="DashboardCtrl as dashboard">
 <div ng-controller="ListCtrl as list" ng-init="list.init(dashboard.listParams)">
  <... Iterate through list.items ...>
 </div>
</div>

Reading a few articles, I saw that using ng-init is not good, and should be used only for lists initialisation. 阅读一些文章,我发现使用ng-init不好,应该仅用于列表初始化。 Is there a better approach, without using ng-init ? 有没有不使用ng-init的更好的方法? Or is this just ok 还是这样就可以了

Consider using a directive instead of just attaching a controller directly to a DOM element. 考虑使用指令,而不是仅将控制器直接附加到DOM元素。 A directive allows you to explicitly handle passing data between controllers without relying on global state (which many solutions using services effectively rely upon). 指令允许您显式处理控制器之间的数据传递而无需依赖全局状态(使用服务的许多解决方案都有效地依赖于全局状态)。

You would want to create a directive that accepts some sort of configuration, which you could then pass via an attribute. 您可能想创建一个接受某种配置的指令,然后可以通过属性进行传递。

angular.module('yourApp').directive('yourList', function () {
  return {
    bindToController: true,
    controller: 'ListCtrl',
    controllerAs: 'list',
    scope: {
      params: '='
    }
  };
});
<div ng-controller="DashboardCtrl as dashboard">
  <your-list params="dashboard.listParams"></your-list>
</div>

The params property will then be available on ListCtrl 's scope. 然后, params属性将在ListCtrl的作用域中可用。 To handle the template used by your directive, you could use a separate partial, or you could use transclusion to keep the elements in your main template. 为了处理您的指令使用的模板,你可以使用一个单独的部分,或者你可以使用transclusion保持的元素在你的主模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM