I created a ListCtrl
, responsible for fetching data from server and paginating it (it will work for ALL my resources). However, It must receive a few configurations
prior to setup the Path to the resource, default limit, and so on...
The way I thought doing it, is to use my ListCtrl inside a bigger Controller, but initialising it with a few params like this:
<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. Is there a better approach, without using ng-init
? Or is this just ok
Consider using a directive instead of just attaching a controller directly to a DOM element. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.