Invoking a directive function with a return value from a controller

I am working on a directive that contains a form with a simple input. I have multiple instances of this directive on the same page (index.html). Outside of these directives, there is a button that, when clicked, should gather data from all the inputs within the directives.

Initially, I attempted to implement a solution found in a question on Stack Overflow about calling methods defined in AngularJS directives. However, I faced difficulties when trying to apply it to multiple directives simultaneously. I also experimented with accessing child elements using $$childHead, but later discovered that this approach was not recommended and stopped functioning as expected.

What would be the most effective method to achieve this goal?

Below is a simplified version of my code:

index.html:

    <div ng-repeat="item in data">
        <h1> {{item.name}} </h1>
        <my-dir info=item >/my-dir>
    </div>
    <input type="submit" value="Save" ng-click="save()" />

Directive:

    app.directive('myDir', function() {
      return {
        restrict: 'E',
        scope: {
            info: '='
        },
        templateUrl: '<input type="text" ng-model="myfield" />',
        link: function(scope, element, attrs) {
                scope.getData = function(){
                    var field_data = scope.myfield;
                    return field_data // not sure if needed
                }
        }
      };
    });

Controller:

    $scope.save= function(){
        // Call the getData function of the directive or get 
        // the data needed somehow and do something with it
    }

Answer №1

To achieve the desired outcome, it is recommended to integrate data as a two-way binding parameter within the directive, similar to how ng-model is commonly used in angular's standard directives.

... scope: { info: '=', data: '=' }, ...

Subsequently,

<my-dir info="item" data="data[0]" ></my-dir>
<my-dir info="item" data="data[1]" ></my-dir>

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

Issue 404: Trouble sending form data from React to Express

I'm facing an issue when trying to send form data from a React frontend to my Node.js/Express backend. The problem seems to be related to a 404 error. I've included only the relevant code snippets below for reference. Function for submitting the ...

What is the best way to access the front camera on both Android and iOS devices in order to capture a photo using Vue.J

I am currently developing a PWA Vue.Js application and I am trying to implement a feature that allows users to take a picture with the front camera on their mobile devices. Although I have managed to write code that works on my desktop browser, I have bee ...

How to properly display an Angular Template expression in an Angular HTML Component Template without any issues?

When writing documentation within an Angular App, is there a way to prevent code from executing and instead display it as regular text? {{ date | date :'short'}} Many sources suggest using a span element to achieve this: <span class="pun"&g ...

I require the capability to retrieve JSON data from beyond the confines of the function

After searching, I was unable to locate it. In my possession is a javascript file and a separate file named data.json. data.json { "today": [ { "id": 1, "title": "Note 1", "date": "21.05.2019", "text": "Lorem ipsum dolor sit ...

After removing an item from the array, React fails to display the updated render

As a newcomer, I am struggling with a particular issue. I have implemented a delete button for each item in a list. When the button is clicked, the object in the firstItems array is successfully deleted (as confirmed by logging the array to the console), b ...

Display a Popup at 5PM without the need for a page refresh, updating in real-time

After searching extensively online, I was unable to find a suitable solution for my issue. What I am aiming for is to have a popup appear on my page every day at 5:00 PM without the need to refresh the page. If I happen to access the page before 5:00 PM an ...

Performing two API calls using Jquery to fetch distinct dynamic elements within two nested $.each loops

There's an API link that contains crucial data about phone brands. From this initial data, I have to create a second API call for each brand to gather more detailed information. For example, the first JSON file (urlphonebrands) lists 3 phone brands - ...

How to replace text using jQuery without removing HTML tags

One of the functions in my code allows me to replace text based on an ID. Fortunately, this function is already set up and working smoothly. $('#qs_policy .questionTitle').text("This text has been updated"); However, there is another ...

Effortless AJAX Submission and MySQL Data Refresh

I've hit a roadblock and can't seem to figure things out. I'm getting rid of my current code because it's not working well across different browsers, particularly when it comes to ajax submission. Could someone please provide me with a ...

Calculate the total value of a certain field within an array when a specific condition is satisfied

I have two sets of data. I am looking to calculate the total time_spent for each course_id that appears in both set 1 and set 2. let set1 = [ { instructor_id: 7, course_id: 19, lesson_id: 1, time_spent: 0 }, { instructor_id: 7, course_id: 19, lesson_ ...

Grabbing an AJAX Request

Currently, I am working on a Firefox extension that is designed to analyze the HTML content of web pages after they have been loaded in the browser. While I have successfully captured events like form submissions and link clicks, I am facing an issue wit ...

How to transform an array into a collection of objects using React

In my React project, I encountered the following data structure (object of objects with keys): const listItems = { 1:{ id: 1, depth: 0, children: [2,5] }, 2:{ id: 2, depth: 1, children: [3,4], parentIndex: 1, disable ...

Including extra js files disrupts the jQuery IntelliSense functionality

After enjoying the benefits of jQuery IntelliSense in VS2008, I decided to add a reference to jQuery UI. However, upon doing so, I noticed that the jQuery IntelliSense disappeared. It seems that referencing another .js file in the document causes this is ...

Guide to uploading a file into a MongoDB database with the help of Mongoose

Currently, I am working on a database application using Node-Express and mongoose. My goal is to enable users to upload various file types such as photos or documents directly into the database. Despite searching extensively for information online, I hav ...

Executing two SQL queries simultaneously in NodeJS can be achieved by using a single statement

app.get("/total", function(req,res){ var q = "SELECT COUNT(*) AS new FROM voters_detail WHERE parties LIKE '%BJP%'"; connection.query(q, function(err, results){ if(err) throw err; var hello = results[0].new; res.send("BJP Was Voted By ...

Using checkboxes to select all in AngularJS

Recently, I started working with Angularjs and came across some legacy code. I am trying to figure out a way to select all checkboxes once the parent checkbox is selected. Here is the parent checkbox: <div class="form-group"> <label for="test ...

The error message displays "window.addEventListener is not a function", indicating that

Recently, I've been dealing with this code snippet: $(document).ready(function(){ $(window).load(function() { window.addEventListener("hashchange", function() { scrollBy(0, -50);}); var shiftWindow = function() { scrollBy(0, - ...

Could it be possible that my consecutive POST and GET axios requests are gradually slowing down?

After chaining the POST and GET calls in my code, I noticed a slight slowdown and was curious if this is normal or if there's a more efficient approach. The delay in displaying the google map marker made me think that pushing the newly created marker ...

Is there a glitch in my redux-saga?

After developing a React Native app, I encountered an issue with my index.ios.js file where I was adding middlewares to the store. import React, { Component } from 'react' import { AppRegistry, } from 'react-native' import { Provider ...

Exploring the potential of jQuery and AJAX for dynamic content generation:

I have developed a jQuery plugin that pulls data from a JSON feed (specifically YouTube) and then presents the results in a DIV. Everything is working well until I need to display the results with different configurations, such as more videos or from anoth ...