Creating a custom 'require' directive in AngularJs results in an error - defining my own path

Imagine having this sample HTML:

<div ng-controller="MyCtrl">    
    <br>
    <my-directive my-name="name">Hello, {{name}}!</my-directive>
</div>

accompanied by a basic controller:

myApp.controller('MyCtrl', function ($scope) {
    $scope.name = 'Superhero';
});

Now in the directive, there is an attempt to change the 'name' using require as shown below:

myApp.directive('myDirective', function($timeout) {
var controller = ['$scope', function ($scope) {
    $scope.name = "Steve";
}];
    return {
        restrict: 'EA',
        require: 'myName',
        controller: controller,
        link: function(scope, element, attrs, TheCtrl) {
            TheCtrl.$render = function() {
                $timeout(function() {
                    TheCtrl.$setViewValue('StackOverflow');  
                }, 2000);                
            };
        }
    };
});

However, an error is thrown stating:

Error: No controller: myName

You can check out the details in this fiddle


On the contrary, if ng-model is used, it actually works. Explore the working example in another fiddle

According to resources like this article, when utilizing 'require' in a directive, a controller needs to be present.

Hence, the question arises:

Is the approach being taken incorrect? Should something else be done instead?

Answer №1

Finally, success!

Essentially, my objective is to achieve 'Communication between directives using controllers'. I came across an informative article that shed light on this topic and guided me through it:

The implementation:

<div ng-controller="MyCtrl">
 <br>
 <my-directive my-name>Hello, {{name}}!</my-directive>
</div>

In the above code snippet, we have two directives: my-directive and my-name. Within my-directive, I invoke a function from the controller of the my-name directive utilizing the require property.

Directive for MyDirective:

myApp.directive('myDirective', function($timeout) {
 return {
  require: 'myName',
  link: function(scope, element, attrs, myNameCtrl) {
   $timeout(function() {
    myNameCtrl.setName("Steve");
   }, 9000);
  } // End of link
 }; // return
});

Directive for MyName:

myApp.directive('myName', function($timeout) {
    var controller = ['$scope', function ($scope) {
        $scope.setName = function(name) {
            $scope.name = name;
            console.log("Inside $scope.setName defined in the directive myName");
        };

        this.setName = function(name) {
            $scope.name = name;
            console.log("Inside this.setName defined in the directive myName");
        };
    }];

    return {
        controller: controller,
        link: function(scope, element, attrs, localCtrl) {
            $timeout(function() {
                localCtrl.setName("Charles");
            }, 3000);
            $timeout(function() {
                scope.setName("David");
            }, 6000);
        }
    };
});

Fascinating approach with effective results. Feel free to experiment by checking out this fiddle.

Additionally, you can establish communication between directives using events. Take a look at this answer on SO for more insights.

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

How to make a straightforward task list using ExpressJS

As a beginner, I am attempting to create a basic todo list using ExpressJS. Currently, my goal is to simply display some hardcoded todos that I have in my application. However, I seem to be struggling to identify the mistake in my code. Any assistance woul ...

Issues with the functionality of jQuery's .load() method are causing

I am encountering an issue for the first time. Inside ajax.html, I have the following code in the header: $(document).ready(function(){ $( "#result" ).load( "/loaded.html" ); }); In the same directory, there is a second page named loaded.html: <d ...

A step-by-step guide on simulating a click event on an element in React with the help of jest and react-testing

My component displays the following {list.options && list.options.length > 0 ? ( <div data-testId="MyAlertText" onClick={onAddText}> Add Text </div> ) : null} When testing, I am executing the following it('Ensure Add Text lin ...

struggling to apply a background color on the canvas with the combination of jspdf and chartjs

Upon exporting a bar chart to PDF using the jspdf plugin, I encountered an issue where the white bars on the chart were not visible due to the transparent background of the PDF. To address this, I added a gray background color to the container, assuming it ...

Removing Arcs from a Map in Leaflet

On my map, I use arc.js to draw trade routes between countries as arcs. Each arc represents a different year, and I want to be able to update them based on the selected year. This is how I create the arcs: // Draw arcs for each trade route var line_to_ad ...

Struggling to dynamically append additional textboxes to a <div> element using JavaScript

After spending over 12 hours on this problem, I am completely stuck and frustrated. I have tried countless variations and sought out other solutions to no avail. It should be a simple task. My project involves using JQueryMobile 1.2 along with its dependen ...

What is the best way to refresh an angularjs page once the scope has been updated?

I have created a custom directive that captures keyboard events and updates certain objects in the scope based on the keys pressed. The goal is to navigate through an array and display details of the selected row. However, I am facing an issue where the pa ...

While using .map() to display videos from an array, the button ends up playing all videos instead of only the selected

Within this component, I am presenting an array of YouTube videos utilizing react-player. The issue I'm facing is that when the custom play button is clicked, all videos in the array play and pause instead of just the selected one. I am currently uti ...

How can one define a function type in typescript that includes varying or extra parameters?

// define callbacks const checkValue = (key: string, value: unknown) => { if (typeof value !== 'number' || Number.isNaN(value)) throw new Error('error ' + key) return value } const checkRange = (key: string, value: unknown, ...

Javascript shows MongoDB array as undefined, though it exists in the database

I am encountering an issue while attempting to add an ObjectId into an ObjectId array of another Object. The problem arises when trying to push the object into the array, as it returns undefined even though it appears in the JSON dump: https://i.sstatic.n ...

Using jQuery AJAX in combination with PHP to store data in a MYSQL database

I am in search of a jQuery AJAX script paired with a PHP script that can store information when a button is clicked. The jQuery function should have three predefined variables, set before the method call. Although I have completed the basic functionality, ...

Previewing posts on a single page can be done by following a few

Hello there! I have written some code in React.js I am trying to display my blog posts on a single page when the user clicks on the "read more" button. I am fetching this data from a news API and I want to show each post based on its specific ID, which i ...

What is the best way to determine the amount of distinct elements in an array of objects based on a specific object property?

I am working with an array called orders. orders = [ {table_id: 3, food_id: 5}, {table_id: 4, food_id: 2}, {table_id: 1, food_id: 6}, {table_id: 3, food_id: 4}, {table_id: 4, food_id: 6}, ]; I am looking to create a function that can calculate ...

Unable to host static content with express

Currently, I am working with Jade and Express to serve static files. Below is the Express code I am using: app.use(express.static(__dirname + "/frontend")); Additionally, here is the Jade code within my layout.jade file: link(rel='stylesheet', ...

Guide on utilizing async/await in .ts files (Encountering error message: "async functions can only be used when targeting ECMAScript 6 or above")

Initially, my project consisted of only app.js using ExpressJS as the main file with numerous lines of code. My development manager instructed me to refactor the code and move some functions into a separate .ts file (transition from JavaScript to TypeScrip ...

How can I retrieve the postback element from an updatepanel using JavaScript?

Is it possible to identify the postback element within an updatepanel using JavaScript? I attempted the code below, but args.get_postBackElement().id returns as undefined. <script> Sys.WebForms.PageRequestManager.getInstance().add_beginReques ...

Update the state both before and after executing the API call

I'm facing an issue with the setState function where it seems to be getting called again before completing the previous batch of state updates. My data object has the following structure: [{ id: 0, loading: false }] On my webpage, I have toggle butt ...

Updating the first element with new HTML content within an Angular directive - Here's how!

My directive looks like this: .directive('iframeOnload', function() { return { restrict: 'A', link: function(scope, elem){ var spinnerElement = angular.element(' <div id="appApprovalSpinner" class="row t ...

The JavaScript onClick function is unable to identify the object

"Newbie" JavaScript Question:-) I'm struggling with a JS function in my code: <script type="text/javascript"> $(function () { $('.shoppinglist-item-add').ShoppinglistItemAdd(); }); </script> This "shoppinglistI ...

How can we display the first letter of the last name and both initials in uppercase on the JavaScript console?

I'm a new student struggling with an exercise that requires writing multiple functions. The goal is to create a function that prompts the user for their first and last name, separates the names using a space, and then outputs specific initials in diff ...