Utilizing AngularJS to access the corresponding controller from a directive

When I have HTML structured like this...

<div ng-app="myApp">
    <div ng-controller="inControl">
        I enjoy sipping on {{beverage}}<br>
        <input my-dir ng-model="beverage"></input>
    </div>
</div>

and my JavaScript looks like this...

var app = angular.module('myApp', []);

app.controller('inControl', function($scope) {
    $scope.beverage = 'juice';
});

app.directive('myDir', function(){
    return {
        restrict: 'A',
        link: function($scope, element, attrs, ctrl) {

            // Why am I getting undefined when logging the controller?
            console.log(ctrl);

        }
    };
});

Why am I unable to access the controller from within my directive? Why is ctrl returning undefined?


UPDATE: Here's a demo for reference...

Check out the fiddle here: http://jsfiddle.net/billymoon/VE9dX/

Answer №1

It is possible to attach multiple controllers to one app and similarly, multiple directives can be attached to one app as well. If you want to use a specific controller in a directive, you can set the controller property of the directive to the name of the controller you wish to attach, like in this example:

app.directive('myDir', function(){
    return {
        restrict: 'A',
        controller: 'inControl'

        link: function($scope, element, attrs, ctrl) {
            // Why is this logging undefined?
            console.log(ctrl);
        }
    };
});

Answer №2

Even though using require:ngModel, there are better ways to approach this rather than directly tying the directive to the controller. To enable communication between your directive and controller, consider setting and reading from the scope.

HTML:

<div ng-app="myApp">
  <div ng-controller="inControl">
    I enjoy having {{drink}}<br />
    <input my-dir="drink"></input>
  </div>
</div>

JS:

var app = angular.module('myApp', []);

app.controller('inControl', function($scope) {
    $scope.drink = 'asdfasdf';
});

app.directive('myDir', function(){
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            console.log(scope[attrs.myDir]);
        }
    };
});

You can also use my-dir="{{drink}}" and access it as attrs.myDir.

http://jsfiddle.net/8UL6N/1/

Answer №3

By including require: 'ngModel', in my directive, I was able to resolve the issue - I am not certain if there are alternative methods to specify this requirement...

app.directive('myDir', function(){
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function($scope, element, attrs, ctrl) {

            // Why is the value of ctrl logging as undefined?
            console.log(ctrl);

        }
    };
});

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

Make sure to leave a space after a period in a sentence, but do

My question is about fixing spacing issues in text, specifically sentences that lack spaces after a dot. For example: See also vadding.Constructions on this term abound. I also have URLs within the text, such as: See also vadding.Constructions on th ...

How can I display just the time portion of a date in AngularJS?

Hey everyone, I need assistance with displaying only the time value in AngularJS. Check out my Plunker I have fetched the time value using ng-repeat, but I want to display only the time value on my portal. I have tried to display the time value lik ...

Unable to execute multiple instances of Selenium PhantomJS concurrently

I have encountered an issue while using Selenium's node.js API to run PhantomJS instances against a series of web pages. The code that I have written to perform actions on the pages is functioning correctly, but it appears that only one instance of Se ...

The CSRF token in Laravel Blade seems to be unreachable by Vue

Having a blade with the following code snippet. <meta name="csrf-token" content="{{ csrf_token() }}"> <covid-form> </covid-form> Inside the covid-form component, there is a form structure like this: <form @submit.prevent="send"&g ...

Facing an issue with webpack-dev-server where it displays a blank screen

Hello! I am currently in the process of creating my first MERN stack application, using Webpack as the build tool. The main objective is to have Express serving the APIs for the app and webpack-dev-server handling the static content (from my static directo ...

Experiencing an anonymous condition post onChange event in a file input of type file - ReactJS

When using the input type file to upload images to strapi.io, I noticed that an unnamed state is being generated in the React dev tools. Can someone explain how this happened and how to assign a name to that state? state constructor(props) { super(pro ...

Utilize Electron's fs to stream a file directly to an HTML video player while it is being downloaded

I am currently exploring the possibility of using the HTML video player to stream a file from the file system within Electron. My goal is to initiate streaming while the file is still being downloaded. I am uncertain whether my current approach will be ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Kurento's WebRTC feature is currently experiencing difficulties with recording functionality

Currently, I am attempting to capture video using the Kurento Media Server with nodejs. Following the hello-world example provided here, I connected a recorderEndpoint to the webrtcEndpoint and successfully got everything up and running. However, on the se ...

Can you explain the contrast between `/:foo*` and `/:foo(.*)` when used in express routes?

When using Express, it is possible to define endpoints with different paths: app.get('/:foo*', function(req, res) { ... }); app.get('/:foo(.*)', function(req, res) { ... }); Although these two paths may appear similar, what sets them ...

Iterate through the JSON data values using a loop and showcase each one by presenting them in individual cards

I'm having trouble determining which type of loop to use in this situation because I am still learning jQuery and JS. On the result page, I have set up cards to separate each piece of data from the JSON file, but I am unsure how to actually display th ...

Splitting an array into multiple arrays with distinct names: A step-by-step guide

I have a data set that looks like this: [A,1,0,1,0,1,B,1,0,0,1,A,1]. I want to divide this array into smaller arrays. Each division will occur at the positions where "A" or "B" is found in the original array. The new arrays should be named with the prefix ...

Trouble with executing AJAX for API call

My current project is built on CI3 and I have created an API that belongs to a different domain than the application itself. $.ajax({ url: "http://www.example.com/restapi/index.php/api/user", type: "GET", data: {"user_id": user_id} ...

Is it possible for AngularJS to share a service among multiple ng-apps?

I've been working on developing a web app that involves multiple Angular ng-apps, and I want to use the same service code for at least two of them (even though they don't share data but perform similar functions). How can I prevent code duplicati ...

The input given to Material UI autocomplete is incorrect, even though the getOptionSelect parameter already exists

I'm currently working on creating my own version of the Google Places autocomplete found in the Material UI documentation. While I have successfully implemented the autocomplete feature and am able to update my component's state with the result, ...

Discovering which chip has wrapped to the next line in Material UI Autocomplete can be found by closely inspect

Currently, I am working with a Material UI autocomplete feature that functions as follows: My goal is to determine when the fourth chip wraps to the next line within the autocomplete so that I can proceed with additional calculations. Is there a method in ...

Exploring the differences between detecting the XMLHttpRequest object in JavaScript and using the try

When it comes to determining browser support for AJAX, I typically rely on object detection like this: if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } ...

Vue JS: Easily Calculate the Total Sum of All Columns

An example of a query in the backend controller public function show($id) { $structural = DB::table('attendance')->where('payroll_daily_id',$id) ->where('assignment','STRUCTURAL') -&g ...

Wait for the successful $save in AngularJS before redirecting

How can I redirect to my list page after POSTing a form if there are no errors and the data is successfully saved in the database? app.controller('NoteCreateController', ['$scope', 'Note', '$routeParams', '$l ...

The React Modal component seems to be malfunctioning within the context of Nextjs

Out of the blue, this issue popped up and I'm puzzled about why it's happening. I have two modals (with different names) that are identical in structure but only one is functioning properly. Both modals use the React-Modal library. The first moda ...