Tips for effectively passing parameters in nested controllers within AngularJS

Currently, I am facing a scenario where I retrieve data from a REST API in a controller, display that data using ng-repeat, then have to execute another controller within that loop. This involves passing data from the initial controller, performing some operations on it, and then running ng-repeat again.

However, upon inspection through "Inspect Element," it appears that the value stored in the parent controller's parameter is displayed. The issue arises when the value passed to the nested controller is actually the variable name.

See the source code snippets below:

HTML:

<div class="checkbox" ng-repeat="bird in birds">
    <table>
        <tr>
            <td>
                <a ng-href="/birds/{{bird.Image}}" rel="shadowbox"><img ng-src="/birds/{{bird.Image}}" height="200" width="200"></img></a>
                <div ng-controller="imageController" model="{{ bird.AdditionalImages }}">More Images: {{ imageString }}
                    <div ng-repeat="image in images">
                        <a ng-href="/birds/{{image}}" rel="shadowbox[{{ bird.Image }}]">a</a>
                    </div>
                </div>
            </td>
            <td>
                 <table>
                     <tr>
                         <td>
                             <b>{{ bird.CommonName }}</b>
                         </td>
                     </tr>
                     <tr>
                         <td>
                             Spotted at: {{ bird.SpottedAt }}
                         </td>
                     </tr>
                 </table>
             </td>
         </tr>
    </table>
</div>

JavaScript (for nested controller):

anekchidiya.controller('imageController', function($scope, $attrs) {
    $scope.imageString = $attrs.model;
    console.log("images: " + $scope.imageString);
});

Answer №1

To implement this functionality, you can pass your scope into a directive, which will result in the creation of an isolated scope.

For instance:

Controller

(function(){

function Controller($scope) {

  $scope.data = [{
    name: 'john',
    age: '26'
  }, {
    name: 'paul',
    age: '24'
  }, {
    name: 'titi',
    age: '32'
  }];

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

Directive

(function(){

  function customDirective() {
      return{
        restrict: 'AE',
        template: '<h3>Age : {{age}}</h3>',
        scope: {
          age: '='
        }
      };
  }

angular
  .module('app')
  .directive('customDirective', customDirective);

})();

You can then use your directive inside an ngRepeat by passing relevant data:

HTML

  <body ng-app="app" ng-controller="ctrl">

    <div ng-repeat="item in data">
      <h2>Name : {{item.name}}</h2>
      <custom-directive age="item.age"></custom-directive>
    </div>

 </body> 

As a result, using an isolated scope in a directive allows you to create complete components or widgets.

This enables you to build custom components and easily pass specific data as needed.

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

Issue with docker-composer module not being detected specifically on windows operating system

We are currently in the process of setting up a container running node.js with docker (specifically docker-compose, as we plan to incorporate mongodb later). Our approach involves copying the package.json in the Dockerfile and then creating a volume mount ...

Using jQuery to toggle visibility of various elements without needing specific identifiers

I have coded a HTML and JS snippet for displaying and hiding a div element, which is currently functioning correctly. However, I want to be able to use multiple boxes on a single page and I need a way to determine which box-header was clicked. Is there a ...

Broaden the default className attribute of the component

Greetings! I'm currently using Bootstrap with React and I am trying to figure out how to extend my component by passing className props deeper. Within my atom component, I have two separate files. The first one contains the component declaration. B ...

Is it possible to incorporate a selection box along with the Raycaster in Three.js?

In my GLTF scene, I have been exploring the use of the example selection box (code) to select multiple meshes. Unfortunately, the current approach is providing inaccurate results as it selects based on the centroid of each mesh and includes meshes that ar ...

Verify the channel where the bot is currently active and dispatch a message

I've been attempting to set up my bot to send a message when it joins a guild, but for some reason, it's not functioning as expected. Here is what I have tried (along with some other variations): const { PermissionsBitField } = require('dis ...

Halt the program's process until the ajax request has finished

Struggling with what seems like a common issue of the "Asynchronous Problem" and finding it difficult to find a solution. Currently, I am working on a custom bootstrap form wizard which functions as tabs/slideshow. Each step in the wizard is represented b ...

When the button is clicked, the ng-click event will trigger the addClass function, but only on the second click

My bootstrap alert has this structure: <div id="errorAlert" class="alert col-md-6 col-md-offset-3 fadeAlert" ng-if="itemExistsAlert"> <button type="button" class="close" data-dismiss="alert">&times;</button> <p>{{alertM ...

The post feature is not delivering the object as expected

I have created a Login page that is supposed to post Username and Password using Axios. I wrapped the username and password into an object as shown in the code below, but when I submit the form, I receive a "201" response. Everything seems to be working fi ...

In the process of developing a matchmaking feature

Currently, I am working on a matchmaking system to find suitable opponents based on a user's trophies. Everything seems to be working fine until the if condition is triggered, which results in an infinite loop. const UserProfile = require("../sch ...

Setting up proxy middleware in an express application

My application is structured with a frontend server (React) serving static files and a backend server (Express). I have noticed that custom header requests trigger preflight requests, causing latency in my application. My goal is to eliminate these preflig ...

Here are some tips for retrieving information from a JavaScript object

My goal is to extract the values of free_time, done_ratio, criticalTask, and dependency from a JavaScript object for each task. I attempted to achieve this, but unfortunately, it didn't yield the desired results. var mock_data_allocation = {"alloc ...

Modifying characteristics of a duplicated object will affect every object

After loading an OBJ file, I created a clone of it in an array. However, when I attempt to change the vertex color of one clone, all the clones are affected. How can I create independent clones with unique attributes? var oload = new OBJLoader(); oload.loa ...

How can nunjucks templates be accessed from NPM (node modules)?

Is there a solution to make nunjucks imports/includes resolve from the NPM node_modules directory? Let's say we have installed a package as follows: npm i -S @example/cards Now, we need to import from it in a template like this: {% import "@exampl ...

Encountering a 404 Not Found issue while trying to add scripts with Node.js

I am currently working with a node server and an HTML file, where the default route is being directed. server.js /** * Created by Creative Coder on 10/26/2015. */ var express = require('express'); var mysql = require('mysql'); var a ...

Retrieve the Vue object nested within another object and log it in the console

I have a variable called 'file' in my Vue application. When I use console.log to inspect its contents, it displays as shown in the image below: console.log(file); https://i.sstatic.net/Zr2KL.png However, when I attempt to view the contents of ...

Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" fo ...

Organize your blog content by utilizing post IDs as the designated id attribute

What is the best way to format blog posts and comments in HTML so that I can easily manipulate them later using jQuery/Javascript for tasks like updating, deleting, or making Ajax calls? I am considering using the IDs (primary keys in the database) of the ...

Creating a 24-hour bar chart using Flot Javascript, showcasing data points at each hour mark

I am attempting to create a 24-hour bar graph using Flot Charts, with a value corresponding to each hour. It seems that Flot utilizes epoch time for hour values. However, after running the code below, I encounter an issue where the chart does not display a ...

What is the best way to link this to a function in AngularIO's Observable::subscribe method?

Many examples use the Observable.subscribe() function in AngularIO. However, I have only seen anonymous functions being used like this: bar().subscribe(data => this.data = data, ...); When I try to use a function from the same class like this: update ...

Adding a custom class to a select2 dropdown: How can it be done?

I have customized select2 using CSS with its general classes and IDs. Currently, I am attempting to customize a specific class that will be assigned to select2 and then applied in the CSS. The problem lies not within the select itself, but within its dro ...