Sharing a controller between directives in AngularJS

While trying to implement an angularjs directive, I encountered some difficulties in sharing a controller between directives

I am unable to access the enterUser directive from the controller below

app.directive('entires', [function () {
  return {
    restrict: 'E',
    replace: true,
    scope : {
      user : '='
    },
    require : '^?enterUser',
    template:"<div><b>Time : </b>{{user.name}}  <b>Task :</b> {{user.age}} <a ng-click='delete(user);'><u>Delete Entry</u></a> <br></div>",
    link: function (scope, iElement, iAttrs, enterUserctrl) {
     console.log(ctrl)
    //At this point, 'enterUserctrl' is returning as undefined..
    //I would like to be able to call the delete function from here
    enterUserctrl.delete(user); 


    }

  };
}])

View the current working fiddle here

Answer №1

I made some adjustments to your code. The main errors were: enter-user should wrap entires for Angular to locate it with require. Additionally, you need to utilize transclude in this scenario.

Please review the updated code below:

app.directive('enterUser', function () {
    return {
        restrict: "A",
        transclude: true,
        templateUrl: 'enter-user.html',

        controller: function ($scope) {

            $scope.addToList = function (name, age) {
                if (typeof $scope.userName != 'undefined' && typeof $scope.userAge != 'undefined') {
                    $scope.nameList.push({
                        name: $scope.userName,
                        age: $scope.userAge
                    })
                    $scope.userName = '';
                    $scope.userAge = '';
                }
            };

            this.delete = function(user) {
                if (typeof user != 'undefined') {
                    $scope.nameList.pop();
                }
            };
        }
    };
});

enter-user.html

<div>
    <b>Name: </b>
    <input ng-model='userName' type='text' />
    <br>

    <b>Age  : </b> 
    <input ng-model='userAge' type='text' />
    <br>

    <span class='right'><button ng-click='addToList(userName, userAge);'>Add to List</button></span>

    <!-- insert trascluded content here -->
    <div ng-transclude></div>
</div>

entires directive

app.directive('entires', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            user: '='
        },
        require: '^enterUser',
        templateUrl: "entires.html",
        link: function (scope, iElement, iAttrs, enterUserCtrl) {
            scope.delete = function(user) {
                enterUserCtrl.delete(user)
            }
        }
    };
});

index.html

<div enter-user>
    <b><u>Here is my entries listed </u></b>
    <div ng-repeat="user in nameList">
        <entires user="user"></entires>
        <br>
    </div>
</div>

Demo Plunker

One more thing to note is that your delete function may not be functioning properly. Just a minor detail to watch out for.

Answer №2

Looking at the code, the

<div enter-user></div>
is clearly separated from the second directive called entires.

If the entires directive relies on the parent directive enterUser, the structure should ideally look like this:

 <div enter-user>
      <div ng-repeat="user in nameList track by $index">
          <entires user="user"></entires>
      </div>
   </div>

For a better understanding, you can refer to THIS demo.

^ – This symbol indicates that the directive will search for parent elements if it's not found on the current element.

In the child directive, we have:

require: '^?enterUser',

If the ? is removed, an error will occur indicating that the parent directive cannot be found. So, caution is advised here.

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

Guide on how to modify the color of a single row within a table with just a click

My table structure is as follows: <table> <tr> <td>A1</td> <td>A2</td> <td>A3</td> <td>A4</td> </tr> <tr> ...

Having trouble retrieving selected values from a CheckboxList in JavaScript

In my asp.net application, I have a checkbox list that is defined as follows: <asp:CheckBoxList ID="chbUserType" RepeatDirection="Horizontal" runat="server"> </asp:CheckBoxList> I have populated this checkbox list using th ...

Design a customizable input field to collect HTML/JS tags

I'm looking to incorporate a similar design element on my website. Can anyone offer me some guidance? Check out the image here ...

ng-repeat not functioning properly with FileReader

Here is a look at how my view appears: <body ng-controller="AdminCtrl"> <img ng-repeat="pic in pics" ng-src="{{pic}}" /> <form ng-submit="postPic()"> <input id="photos" type="file" accept="image/*" multiple/> <button> ...

Updating the LockedException from Spring Security to return a different status code to Angular.js

I am currently using a combination of Spring 4, Hibernate 4, and Spring Security (RESTFul Webservice API) along with Angular on the front-end. I am relatively new to all of this. The failure handler in my code is structured as follows: @Component ...

Using Highstock for Dynamic Data Visualization in Web Applications

Looking to create a chart using data from a MySQL database that includes timestamps and temperature readings. The timestamp format is '2015-06-11 22:45:59' and the temperature is an integer value. Unsure if the conversion of the timestamp to Java ...

Is there a way to make my modal appear only when the "New" option is clicked?

Is there a way to make my modal in VueJS open only when I click on the "New" option? <select v-model="input.des" @change="$refs.modalName.openModal()"> <option value="A">A</opt ...

Utilizing AJAX to load a WAV file

One of the tasks I'm working on involves a collection of audio files. When a file from this list is clicked, I want JavaScript to load and display the waveform of that specific audio file. The following function is responsible for drawing the wavefor ...

Enhance User Experience with a Customized Progress Bar using Google Apps Script

I created a Google Sheets cell counter in Apps Script and need help setting up the bootstrap progress bar using the "percentage" variable. GS function cellCounter() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheets = ss.getSheets(); var ...

How to trigger a click event on a div and effectively filter Vuex data in Vue.js?

Currently facing a challenge with exporting the filter function and utilizing it in a vuex store. Everything was smooth sailing until this point. Now, I'm attempting to add an @click event to divs. When I click on a particular brand, such as "Audi," I ...

Utilizing Vue to bind data for asynchronous Axios requests

Having an issue with my Vue function that is triggered by a button click. It makes an axios call, but the problem is that no matter what I type in the textarea (v-model taskCommentBody), it sends the data commentBody as blank. Not sure what's causing ...

Tips for accessing and saving content from a JSON file on your local machine into a variable

Hello all, I'm facing an issue with my script where I have a Json store in a variable. I want to save this json data in a local file to create a standalone and user-friendly website without too many components. Currently, my script looks like this: ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

What's the best way to refresh append() functionality within a modal? I'm currently working with NODE JS and AJAX and

Whenever I click the modal, the append() calls are adding HTML content. But if I try to use empty() or html(), the modal stops appearing altogether. What is the correct approach to creating this modal? function loadModalContent(id) { $('#myModal& ...

In JavaScript, Identify the filename selected to be attached to the form and provide an alert message if the user chooses the incorrect file

I have a form in HTML that includes an input field for file upload. I am looking to ensure that the selected file matches the desired file name (mcust.csv). If a different file is chosen, I want to trigger a JS error. Below is the form: <form name="up ...

Utilize CSS to break apart text (text = white space = text) and align text in a floating manner, allowing

Is there a way to use CSS to create a white space in the middle of text? Currently, I am manually breaking the text, which is not ideal. I am aware that there is a function that allows the text to end and start in another div, but unfortunately, it is not ...

Count the occurrences of x.status being equal to 10 in AngularJS

I have 3 different statuses: 10, 20, and 30. I am trying to determine how many times x.status equals 10 and display that count. My initial approach was something like this: count="x.status" where="x.status == 10" Count: {{value}} <!DOCTYPE html> ...

Vue Js: Creating an array of checkboxes

I have a collection of checkboxes sourced from the main system object where I store all system settings (referred to as getSystem{}). Within this form, I am retrieving information about a User, who possesses an array of roles []. How can I cross-reference ...

The sqlite database is throwing an error stating that it cannot read the property 'firstname' of an undefined value

I'm new to Ionic and I'm attempting to use the Cordova SQLite plugin. Unfortunately, I am having trouble reading a column in my code. I have followed examples, but it doesn't seem to be working. document.addEventListener('deviceready&a ...

Delay loading all images on the page except for the first one until the page is completely loaded

My website has a slider feature that displays images in a sequence, but currently all the images load at once and then get hidden by a script after the page is fully loaded. I tried using CSS to set a fixed height for the slider, which worked on desktop bu ...