Retrieve information from a controller and pass it to a Component in AngularJs

Having an issue with passing data from a controller to a component in AngularJs.

The data is successfully passed to the template component, but it shows up as undefined in the controller!

See below for my code snippets.

The controller

angular.module('testModule')
.controller('testController', ['$scope',
    function($scope){
        var vm = this;
        vm.name = "John";
    }
]);

The component. Problem arises when trying to access vm.name in the console.log(). It returns undefined.

angular.module('testModule')
    .component('testComponent', {
        bindings: {
            "name": '='
        },
        controllerAs: 'ctrl',
        controller: ['$scope', function ($scope) {

            var vm = this;
            console.log(vm);              
            console.log(vm.name);
        }],
        template: "<h2>Hi {{ctrl.name}}</h2>",
    });

HTML

<html ng-app="testModule">
<head>
    <title>Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
    <script src="app.module.js"></script>
    <script src="testController.js"></script>
    <script src="testComponent.js"></script>
</head>
<body>
<div ng-controller="testController as ctrl">
    <test-component name="ctrl.name"></test-component>
</div>
</body>
</html>

For a live demo and reference, please visit the following Plunker link.

If you have any insights or suggestions, I'd appreciate your help. Thank you!

Answer №1

To properly access the component's bindings, it is recommended to utilize the $onInit method.

vm.$onInit = function(){
    console.log(vm.name);
}

Prior to AngularJS 1.6, your approach was feasible. However, with the introduction of preAssignBindingsEnabled in AngularJS 1.6+, prepopulating the controller context has been disabled by default through $compileProvider. If you wish to enable this feature, you can do so by setting the flag as shown below (although not recommended). This change was implemented to align Angular and AngularJS APIs for easier migration towards Angular.

.config(function($compileProvider){
  $compileProvider.preAssignBindingsEnabled(true);
})

Plunker

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

Encountering an error with ResizeObserver.observe when using Next.js and ag-grid to render client side

I designed a product page that includes a searchbar component and a grid component with the ag-grid import and setup. Here is a simplified version of the product page: // Code for dynamic client side rendering import const ProductGrid = dynamic(() => ...

Is it possible to retrieve browser history from Google Chrome using Node.js on a Windows operating system?

I'm currently developing a personal electron app for managing my lifestyle. One of the key features is controlling my daily internet browsing through the app. I am aiming to integrate my Chrome history into the electron app. Could someone recommend a ...

the slider HTML control is missing a value

Exploring the Range Input Type in HTML When adjusting the value on a slider (Range input type), that value is displayed in a textbox. However, making the same adjustment in the textbox does not update the slider's value. Below is the code snippet: & ...

Refreshing the Canvas post-submission

I have created a form that allows users to add notes and sign on a Canvas. However, I am facing an issue with clearing the canvas after submission, as it does not seem to work properly. The rest of the form functions correctly. The goal is to clear both t ...

Transforming Observable into a Promise

Is it considered a best practice to convert an observable object to a promise, given that observables can be used in most scenarios instead of promises? I recently started learning Angular and came across the following code snippet in a new project using ...

What is the best way to save and reload a canvas for future use?

My current setup involves using PDF.js to display PDF documents in a web browser. The PDF.js library utilizes canvas for rendering the PDF. I have implemented JavaScript scripts that allow users to draw lines on the canvas by double-clicking, with the opti ...

Class does not have the capability to deserialize an array

I encountered this issue with my code (see image): https://i.sstatic.net/QxI0f.png Here is the snippet of my code: function CheckLoginData() { var user = []; user.Email = $("#tbEmail").val(); user.Password = $("#tbPassword").val(); $.ajax({ type ...

Detailed enrollment procedure

I am facing an issue with the code in my HTML that validates input types. The system detects empty fields and prevents proceeding to the next step. How can I disable this validation as some of the fields are not required? For instance, the input type < ...

What is the process for taking a website project running on localhost and converting it into an Android web application using HTML, CSS, and JavaScript

Looking for recommendations on how to create an Android web application using HTML, CSS, and JavaScript. Any suggestions? ...

What is the best way to transform React API data into props that can be utilized in different components?

I've been struggling with this issue for quite some time now, unable to understand how to manipulate the data in a way that allows me to use it in other components. Although I can display the data correctly, I'm advised to structure it within a f ...

When transmitting information to the server, the browser initiates four requests

I am encountering an issue with my React component. The problem arises when I try to retrieve the current geographic coordinates, as they are being fetched 4 times consecutively. This same glitch occurs when attempting to send the coordinates to the serv ...

Using the .json method in Angular 7 for handling responses

While attempting to implement the function getProblems to retrieve all problems within its array, I encountered an error message appearing on res.json() stating: Promise is not assignable to parameters of type Problem[]. It seems that the function is ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

What is the best way to create a button that will trigger a modal window to display a message?

I am looking to create a button that will open a modal window displaying a message. However, when I tried to add a label and viewed the page, the desired window appeared on top of the rest of the content. But unfortunately, clicking the button did not prod ...

Efficient ways to clear all input fields within a React div component

import "./App.css"; import { useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import { addUser} from "./features/Users"; function App() { const dispatch = useDispatch(); const use ...

Problems arising from Jquery append functionality

When using the append method, my inner div is only attaching one WHEAT-COLORED-BOX, whereas when using appendTo, my inner div attaches all the required number of WHEAT-COLORED-BOXES. Therefore, in this case, appendTo gives the correct result while append f ...

What is the process of implementing session storage in an AngularJS directive?

I am trying to save values in Angular session storage within an Angular directive, but I am facing an issue where I only receive NULL. Can anyone provide assistance? app.directive('myDirective', function (httpPostFactory) { return { restrict ...

The issue with property unicode malfunctioning in bootstrap was encountered

I have tried to find an answer for this question and looked into this source but unfortunately, when I copy the code into my project, it doesn't display Unicode characters. section { padding: 60px 0; } section .section-title { color: #0d2d3e ...

Error: Node application using Express does not display 'Server Started' message in console upon execution

I'm encountering an issue where I don't see the "Server Start: 3001" message on the console when I run 'node app.js' in the terminal. Below is the content of my app.js file: var createError = require('http-errors'); var exp ...

The screen reader seems to be malfunctioning as soon as I include this particular code

//Finding the height of the header let headerHeight = document.querySelector('header'); let height = headerHeight.offsetHeight; //Adjusting the #navbarNav's top margin to accommodate the header let nn = docu ...