The Binding of Components in AngularJS

Struggling with accessing the item looped from an ng-repeat in a parent component within the scope of a nested component. The parent is a carousel with multiple item components populated by the ng-repeat. Need to be able to access the "item" and a method of the carousel controller ("cr") in the item controller ("it"). Looking for guidance on the correct approach.

carousel.component.html

<slick <!--slick attributes--> >
     <div ng-repeat="item in cr.items">
            <item-component></item-component>
     </div>
</slick>

carousel.component.js

class CarouselController{
  constructor(/*stuff*/){
    'ngInject';    

     this.items =[
       {"something":"The thing 1","otherthing":"The other thing 1"},
       {"something":"The thing 2","otherthing":"The other thing 2"},
       {"something":"The thing 3","otherthing":"The other thing 3"}
     ];
  }

  parentFunctionToCall(item){
    console.log('I called a function on the parent!',item)
  }

  /*other stuff*/
}

export const CarouselComponent = {
  templateUrl: './views/app/components/carousel/carousel.component.html',
  controller: CarouselController,
  controllerAs: 'cr',
  bindings: {
  }
}

item.component.html

<div data-something="{{item.something}}">
  Yo,{{item.otherthing}}!
</div>

<a href="#" ng-click="cr.parentFunctionToCall(item)">
   Trying to call a function on the parent component
</a>

item.component.js

class ItemController{
  constructor($scope,/*stuff*/){
    'ngInject';

     //$scope.it.item & $scope.it.cr are both undefined
     console.log(this);

     //I understand this is the incorrect way but it works
     this.$scope.item = this.$scope.$parent.item;
     console.log(this);
  }

  /*other stuff*/
}

export const ItemComponent = {
  templateUrl: './views/app/components/carousel/item.component.html',
  controller: ItemController,
  controllerAs: 'it',
  bindings: {
    "item":"=",//i can see this as undefined $scope in ItemController
    "cr":"=" //i want to access a method on the parent controller
  }
}

This shows whats up... https://plnkr.co/edit/UG20EtI4KxnVnTe8zzz4?p=preview

Answer №1

When utilizing the controllerAs approach, the traditional $scope is no longer necessary. Instead, you should reference properties with this, especially when working with components.

this.items = [
   {"something": "The thing 1", "otherthing": "The other thing 1"},
   {"something": "The thing 2", "otherthing": "The other thing 2"},
   {"something": "The thing 3", "otherthing": "The other thing 3"}
 ];

For more information, visit https://docs.angularjs.org/guide/component.

Answer №2

Surprisingly simple in the end.. It's unclear why this information isn't emphasized in the documentation, but it's as straightforward as setting an attribute on the child component:

<slick <!--slick attributes--> >
  <div ng-repeat="item in cr.items">
        <!--new item="item" attr-->
        <item-component item="item" call-parent="cr.parentFunctionToCall(item)"></item-component>
  </div>
</slick>

After that, the binding functions as expected. Accessing a parent function works similarly. An event name needs to be included as an attribute (call-parent, though it can be anything). The binding should be added to the child component (as mentioned in @kuhnroyals comment):

...
bindings: {
  item:"=",
  callParent: '&'
}

And some interaction event on the child component like ng-click="it.callParent()"

You can access a working example here: https://plnkr.co/edit/RIOPs6?p=preview

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

Template for child directive failing to reflect scope updates

I am working on a custom directive that includes child directives: <rp-nav> <rp-nav-item cat="1"></rp-nav-item> <rp-nav-item cat="2"></rp-nav-item> <rp-nav-item cat="3"></rp-nav-item> <rp-nav-it ...

Executing a Ruby method on a server using JavaScript - A guide

I'm facing a seemingly simple issue that I can't seem to find a clear solution for anywhere. Essentially, I have a JavaScript application hosted on a server that requires passing information between the JS app and a Rails-built server. The proces ...

Manipulating selected values in VueJs v-select using methods

I am currently working on achieving the following goal: When I select the option "Alle openstaande" (result_id = 0), I want to select all these result_ids: [-1,-2,-3,-5,-7,-8,-11,-12] and deselect result_id 0. The variable mergedResults stores an array o ...

What is the best location for loading large amounts of data in the MEAN+Mongoose framework?

When it comes to the MEAN stack, where is the ideal level to load bulk data? I have a range of 200 to 800 entries across 2 to 3 different types, each requiring its own Mongoose schema. Here are some options for loading this data (please correct any miscon ...

Tips for monitoring the visibility of an element in an angular.js application

It may seem like a typical old question, but for me it's quite unique. In my Angular-based application, the Selenium test fails and throws an error when logging in due to the Loader appearing immediately. The exception message is as follows: unknow ...

Leveraging jquery version 2.2.2 within a grails application

In an effort to ensure compatibility in a Grails project, we are looking to change the JavaScript library versions. We recently added AngularJS 1.5.2, which requires jQuery 2.1+ (source: https://docs.angularjs.org/misc/faq). Our current version of jQuery i ...

Issue with File Input not being validated by Bootstrap Validator

Looking for help with a form field that should only accept .jpg or .png images of a certain file size. The validation doesn't seem to be working when tested with invalid file types. What am I missing? It should function like the example shown here. C ...

The word "yargs" will not activate a command within a script

I have a NodeJs script that requires parsing command line arguments. Here is the code I have written: import yargs from "yargs"; import { hideBin } from 'yargs/helpers'; //.... yargs(hideBin(process.argv)).command('--add-item ...

Building basic objects in TypeScript

My current project involves utilizing an interface for vehicles. export interface Vehicle { IdNumber: number; isNew: boolean; contact: { firstName: string; lastName: string; cellPhoneNumber: number; ...

Learn the process of implementing winston error management in conjunction with the express-async-errors package by utilizing ES6 syntax

Currently, I am utilizing ES6 with Node.js and looking to manage uncaughtException and unhandledRejection utilizing express-async-errors. The documentation advises only requiring the module, but what steps should I take with ES6? // require('express- ...

Javascript essential file for Bootstrap 4

Help with Bootstrap I recently downloaded a web template that is based on bootstrap 4, and it has all the features needed to create a responsive website. However, I have a question regarding the inclusion of a javascript main file (main.js) in the code eve ...

How can I make my modal box appear after someone clicks on selecting a college?

Can someone help me figure out how to display my modal box after clicking into the selecting list? I've already coded it, but I'm struggling with getting it to show up after the click event. Any assistance is appreciated! In the image provided, ...

Upon selecting a checkbox, I desire for a corresponding checkbox to also be marked

I am looking to enhance my current project by incorporating a feature that allows the user to simply check a checkbox with specific content once. For example, I have a recipes page where users can select ingredients they need for each recipe while planning ...

uib-carousel glitching and stuck in never-ending loop

In my HTML, I have the following code snippet: <div style="height: 305px"> <div uib-carousel active="false" interval="50000" no-wrap="true"> <div uib-slide ng-repeat="slide in shoes track by slide._id" index="slide._id"> < ...

Getting started with html2canvas: A beginner's guide

So here's a seemingly simple question... I'm diving into new territory and stumbled upon http://html2canvas.hertzen.com with a straightforward tutorial. After successfully running the command npm install -g html2canvas, I hit a roadblock. Where e ...

html navigation bar is not functioning as intended in my webpage

I'm facing an issue with my navbar menu. I implemented some JavaScript code to make the navbar sticky while the user scrolls, but it's not working as expected. The navbar is not staying sticky when the page is scrolled. Could someone please revi ...

What is the best way to extract a particular key value from a JSON object?

I am completely new to the world of APIs and just starting out with JavaScript. My goal is to retrieve the status of a server from a server hosting panel using an API. In order to achieve this, I need to log in by making a request to /API/Core/Login, extra ...

"Ajax validation is causing the duplication of the HTML page content within an HTML

My PHP username validation with Ajax code seems to be duplicating my HTML page inside an HTML div element, which is used for displaying Ajax errors. Despite trying various solutions and searching on Google, I have not been able to find a resolution yet. Th ...

What is the purpose of importing React from "react" in a .jsx file? Is there any distinction between the .jsx and .js extensions?

Typically, we use it to write JSX syntax within .js files. ...however, since I've already specified the extension as .jsx, why do we still need to import the react module? I've attempted to find the answer, but it remains unclear in all my resea ...

Executing multiple MSSQL queries in a Node.js environment

Currently, I am faced with the challenge of running multiple SQL queries. The issue lies in variables going out of scope due to the asynchronous nature of node.js. I am attempting to find a solution similar to the await keyword available in C#. To clarif ...