A specific Angular directive that necessitates the utilization of another directive that relies on a controller defined within

As I delve into learning angular, custom directives have presented me with a challenge that has left me stumped. Below are the custom directives in question:

/**
 * Created by Lucas on 11/06/2015.
 */
'use strict'

eventsApp

    .directive('greeting',function() {
        return {
            restrict: 'E',
            replace: true,
            template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>",
            controller: function GreetingController($scope) {
                var greetings = ['hello'];
                $scope.sayHello = function() {
                    alert(greetings.join());
                }
                this.addGreeting = function(greeting) {
                    greetings.push(greeting);
                }
            }
        };
    })
    .directive('finnish',function() {
        return {
            restrict: 'A',
            require: 'greeting',
            link: function(scope, element, attrs, controller) {
                controller.addGreeting('hei');
            }
        }
    })
    .directive('hindi',function() {
        return {
            restrict: 'A',
            require: 'greeting',
            link: function(scope, element, attrs, controller) {
                controller.addGreeting('नमस्ते');
            }
        }
    });

Although these directives are functioning as expected, trouble arises when the greeting controller is modified to accept an external controller via an attribute like so:

.directive('greeting',function() {
        return {
            restrict: 'E',
            replace: true,
            template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>",
            controller: '@',
            name: 'ctrl'
        };
    })

This adjustment would necessitate references in the HTML code as follows:

<!DOCTYPE html>
<html ng-app="eventsApp">
<head lang="en">
<meta charset="UTF-8>
<title>Event Registration</title>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/app.css"/>
<'/'body>
<greeting ctrl="GreetingController">
    <div finnish hindi></div>
</greeting>

<script src="lib/jquery.min.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="lib/underscore-1.4.4.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/GreetingController.js"></script>
<script src="js/directives/greeting.js"></script>
<script src="js/filters.js"></script>
<script src="lib/bootstrap.min.js"></script>
<'/'body>
   </'/html>

The moment these changes are made, the other directives cease working and Angular throws up the following error:

Error: [$compile:ctreq] Controller 'greeting', required by directive 'hindi', can't be found!

I am certain there must be a solution to rectify this issue, but being new to Angular, I find myself at a loss.

Answer №1

In order to retrieve the controller as an attribute, it is essential for the attribute name to match the directive name:

<greeting greeting="GreetingController" spanish="" french=""></greeting>

For a working example, refer to this 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

What is the best way to integrate plaintext JSON configuration into my Angular webpack app?

I am currently working on developing a web application that is driven by configuration using webpack and Angular while also incorporating Babel and ES6. One challenge I keep facing is the need to have my config.json file separated into its own chunk and a ...

Transferring a list of files from Callback folder

I am struggling with a function that is supposed to retrieve and list all the files in a specific folder. However, I am facing issues when trying to push out these files through an array. Something seems to be going wrong in my code as I receive an error w ...

Submit button functions properly in Chrome, yet facing issues in Firefox and IE

My submit button is clickable in Chrome but not in FF or IE. I suspect the formatting of the button may be incorrect. Any help would be greatly appreciated! <button> <img src="http://button_image.png" onclick="mySubmit();" ></button> Th ...

Breaking down arrays in Typescript

Let's say I have an array like this: public taskListCustom: any=[ {title: 'Task 1', status: 'done'}, {title: 'Task 2', status: 'done'}, {title: 'Task 3', status: 'done'}, {title: 'Task ...

What is the best way to transform a JavaScript array into a neatly formatted JSON string?

Imagine having an object structured as follows: var test = { jsonString: { groups: ['1','2','3','4','5'] } } How could you transform it into a JSON string like this? var test = { jso ...

Live updates to database tables based on checkbox selections

Utilized a repeater to showcase a list on the screen. I incorporated an <asp:checkbox for each record, with the intention of having it instantly update in the corresponding table in the database based on whether it was clicked or not.....My progress so ...

The POST function isn't functioning correctly within the temp.js file

My issue with the post method: var newUser = { "user5" : { "name" : "john", "password" : "qwerty123", "profession" : "developer", "id": 5 } } app.post('/createUser', function (req, res) { // Reading existing use ...

Using Vue JS to showcase array data in a dropdown menu with Bootstrap-vue

Currently, I have an array of JSON data structured like this: loggers = [{ "allAvailableLevel": ['WARN', 'DEBUG', 'INFO'], "level": "WARN", "logger": "com.test1", "status": "success" }, { ...

What could be the reason for my dropdown not submitting the form?

Check out my code below: <div class="center"> <p> Choose an item: </p> <div class="dropdown"> @using (Html.BeginForm("Start", "Home", FormMethod.Post, new { name = "form", id = "form" })) { @Html ...

Error encountered: Unable to call JavaScript across processes during the click command in Selenium IDE

My current setup involves using an SPA built on AngularJS 1 and Selenium IDE 2.9.1 for functional testing. One of the challenges I am facing is with a button that has an onclick handler on a form. Whenever I try to click this button during a test scenario ...

The issue with jQuery Promise not functioning correctly following an AJAX request

I have defined my Promise like this: myFunc = function() { $.getJSON("./rest/api/some/url", function(json, textStatus) { console.log("AJAX call hit!"); }); }; $.when(myFunc()).then(function() { console.log("Then block hit!"); }); When ...

Issues with displaying the correct date in AngularJS, possibly related to moments.js

I'm currently working on a project that involves Bootstrap 4. I've been attempting to integrate Angularjs with moments.js, but unfortunately, I haven't had much success. This is the HTML code I've used: <input type="date" name="som ...

JQuery struggling to attach blur event to every single <input> element on a webpage

I'm attempting to attach a blur event to all "input" elements on the page, including those nested inside iframes. While I've successfully attached blur events to input elements outside of iframes, I'm facing challenges with elements within ...

Using Sequelize to Link Two Columns Between Tables

In my sequelize database, I have the following table settings: const Accounts = sequelize.define('Accounts', { name: DataTypes.STRING, }); const Transfers = sequelize.define('Transfers', { value: { type: DataTypes.DECIMAL(10, ...

React Grid by DevExtreme

Does anyone have a solution for adjusting the fontSize of the TableHeaderRow in a DevExtreme React Grid? Here is some code from a specific website () that I've been exploring: import * as React from 'react'; // Other imports... const Ad ...

Encountered an error while building CSS Modules for a Vue.js project

Working on a project in Vue.js, I decided to incorporate CSS modules for my local styles (for sass and scss). However, I continuously encounter a 'Failed to compile error' related to the CSS Loader validation process. Despite attempting various ...

Animation with Vue3 Suspense: From Parent to Child

I want to utilize Vue3 Suspense to trigger a loading state at the parent level that activates animations in the children. Once the request is completed at the parent level, I aim to remove the animation from the children. App Header: router-view(v-slot=&q ...

NativeScript has just faced a critical issue: an Uncaught ReferenceError has occurred stating that the variable __UI_USE_EXTERNAL_RENDERER__ is not

While working on iOS on my Mac, I encountered an unexpected error. ***** Fatal JavaScript exception - application has been terminated. ***** NativeScript encountered a fatal error: Uncaught ReferenceError: __UI_USE_EXTERNAL_RENDERER__ is not defined at (f ...

What is the best way to reassess the quantity of a specific element once a for loop has finished executing?

const removeBtnCustom = document.querySelectorAll('.customRemove'); for(let i=0; i<removeBtnCustom.length; i++){ removeBtnCustom[i].addEventListener('click', ()=>{ const itemToDelete = document.querySelectorAll('. ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...