Guide to connecting to various controllers in Angular

To streamline the process of fetching data from the server and paginating it for all resources, I developed a custom ListCtrl. However, before setting it up, this controller needs to receive certain configurations such as the path to the resource and default limit.

My initial idea was to incorporate the ListCtrl within a larger controller and pass necessary parameters 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>

After some research, I came across articles suggesting that using ng-init is not ideal and should only be utilized for list initialization purposes. Is there a more efficient approach that does not involve ng-init? Or is this current method acceptable?

Answer №1

It is recommended to utilize a directive instead of simply attaching a controller directly to a DOM element. By using a directive, you can effectively manage data passing between controllers without depending on global state, as many solutions utilizing services often do.

To achieve this, you should create a directive that can accept a certain configuration, which can then be passed through 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 now be accessible on the scope of ListCtrl. To handle the template used by your directive, you can opt for a separate partial, or you could utilize transclusion to maintain the elements in your main template.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on displaying the marker location on a map when hovering over a div element, similar to the method used by AirBnb

In the left side div of my page, there are items such as images, titles, details, and addresses. On the right side, I have a Leaflet Map that shows markers of these addresses taken from the left side items. What I want is to display the marker locations on ...

Is there a method to ensure that the window event always gets triggered before any other events?

Is there a way to make the window event trigger first when clicking on #myDiv? (function ($, w, d) { $(d).ready(function () { $(w).click(function() { alert('window has been clicked'); }); $('#myDiv').cl ...

What is the reason behind installing both Typescript and Javascript in Next.js?

After executing the command npx create-next-app --typescript --example with-tailwindcss my_project, my project ends up having this appearance: https://i.stack.imgur.com/yXEFK.png Is there a way to set up Next.js with Typescript and Tailwind CSS without i ...

Adjusting the Aspect Ratio of an Embedded YouTube Video

<!DOCTYPE HTML> <head> <style> body { overflow: hidden; margin:0; } </style> </head> <body> <iframe id="video" src="https://www.youtube.com/embed/U4c9bBeUe4M?modestbranding=1&sh ...

What steps can be taken in Next.js to display a 404 page when data is not retrieved from the Wordpress admin?

I am working with JSON data that looks like this: [ { "taxonomy_slug": "product_cat", "taxonomy_name": "Categories", "frontend_slug": "product-category" }, { ...

Extracting Data from Input Box Using Query

In my HTML setup, I have five <textarea> tags with IDs text1,text2,text3,text4, and one additional <textarea> tag with ID output. I want to query based on the values of text1,text2,text3,text4 (referred to as field1, field2, field3, field4). F ...

Determining the parameter type for the directive

How can you specify the types of parameters for the directive in AngularJS? Which type should be used for & binding? Refer to ngdoc or jsdoc for an example code. UPDATE: I am looking for answers to the following questions * @param {<< What sh ...

Switching between Login Form and Register Form in VueJS template

Recently, I attempted to switch between the 'Login Form' and 'Register Form' using code that I found on codepen Flat HTML5/CSS3 Login Form. While the code functioned properly on its own, when integrated into a Vue Template, the form fai ...

What is the best way to convert a List of objects to JSON using a dynamic variable?

I have a need to serialize a list of objects in a specific way: Imagine I have the following C# class: public class Test { public string Key; public string Value; } List<Test> tests; When I serialize this list (return Json(tests.ToArray()) ...

What is the solution to rectifying the issue with graphql codegen?

Upon running the command "yarn graphql-codegen," an error occurred and I am unsure how to resolve it: % yarn graphql-codegen yarn run v1.22.4 warning package.json: No license field $ /Users/xxx/node_modules/.bin/graphql-codegen ✔ Parse Configuration ⚠ ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...

Creating a menu with items and listeners from a kmllayer - a step-by-step guide

Currently, I am working with a map that includes a kmllayer. This layer has been added using the following code: ctaLayer = new google.maps.KmlLayer('http://www.npd.no/engelsk/cwi/pbl/en/aFactGlobe/disc/ActivityStatus_Producing_labels.kml'); ...

What's the best way to ensure that the theme state remains persistent when navigating, refreshing, or revisiting a page in the browser?

Is there a way to ensure that my light/dark theme settings remain persistent when users reload the page, navigate to a new page, or use the browser's back button? The current behavior is unreliable and changes unexpectedly. This is the index.js file ...

HTML script tag failing to load

As a beginner in using scripts in HTML, I'm currently following a tutorial that suggests loading the script after the body for certain reasons. In my own code, I found that I need to place the script both in the head section and after the body. Remov ...

Guidelines for dynamically switching between two buttons (function/text) depending on an external factor (such as the number of items bought)

I'm exploring a previous concept of toggling between two buttons conditionally in a CRA. import ... const ... export const Index = () => { // Setting up boolean state to toggle buttons conditionally const [reachMax] = React.useState(id <= ...

Issue with JavaScript: Flag set to false does not halt the simple animation

My goal is to initiate animations when the mouse is pressed down and then immediately halt them once the mouse is released. Upon pressing the mouse, I set a flag to true which triggers the animation of the corresponding button that was clicked. However, t ...

Clones are made sortable instead of arranging them in a specific order

I have a list that can be sorted with some customizations. However, I am facing an issue where the items in the list get duplicated every time I try to sort them. When I pull one item to sort it, another copy gets added automatically. I am struggling to u ...

Using HttpClient to display data on the DOM

Presented here is a list of employees sourced from my imitation db.json. I am attempting to display it in the DOM. When I use {{employee}} within the loop in app.component.html, it displays a list with 2 items, each showing as [object Object]. However, if ...

Creating HTML code from a website by utilizing XML

As someone who is not a developer and doesn't have much knowledge about java, I am seeking advice on potential solutions to achieve the following. This web hosting service enables users to retrieve data from their XML spreadsheets and embed them anyw ...

the pop-up modal function is malfunctioning

I can't get my pop up to work properly. When I click the button, the screen dims as if a pop up is going to appear, but nothing shows up. Can someone please assist me with this issue? Here is the HTML file: <!DOCTYPE html> <html lang="en"&g ...