Transferring a JSON object along with a function to the controller of another directive

I am facing a challenge in sending a JSON object with a function template from app.controller to another directive controller. I have chosen to pass this variable as an attribute of the inner directive's element. The issue arises when attempting to access the object within $attr.valueAtt in my directive controller, as it only returns "[object Object]".

This is my code snippet:

var value = (
  [{
     functionLabel:'Fun', 
     functionTemplate: function(param1,param2){
       alert(param1);
     }, 
     functionParams: ['PARAM1','PARAM2']
  }]);

Subsequently, I include it in the controller as an attribute of the directive element:

angular.element(document.getElementById('space-for-modals'))
         .append($compile("<modal-dialog visible='true' data-backdrop='static' valueAtt='"+value+"'></<modal-dialog>")($scope));

When trying to retrieve "value" in my directive controller:

 $scope.functions=  $attrs.valueAtt;

However, within $scope.functions, only "[object Object]" is stored. Is there a technique available to successfully send a function template from one controller to another for future calling?

Answer №1

Issue arises when the JavaScript conversion of value to a string results in "[object Object]" instead of the intended object reference. To resolve this, store the object in the scope and then utilize its name in the HTML attribute. Consider this approach:

  var scope2 = scope.$new();
  scope2.foo = [{
     label:'Fun', 
     fn: function(param1, param2){
       alert("Callback function says: " + param1)
     }, 
     params: ['PARAM1', 'PARAM2']
  }];

  angular.element(document.getElementById('space-for-modals'))
     .append($compile("<modal-dialog visible='true' data-backdrop='static' value-att='foo'>Modal dialog</<modal-dialog>")(scope2));

Within the modal dialog link function, the value-attr can be dereferenced to obtain foo:

link: function(scope, elem, attrs) {
  scope.functions = scope[attrs.valueAtt];
}

In the dialog controller, access the functions member. Note that it will only be available after the link function has been executed, necessitating the use of a watch:

  $scope.$watch('functions', function(functions) {
    if (functions == null)
      return;
    var ft = functions[0];
    ft.fn.apply(null, ft.params);
  });

Check out the demo.

The practice of compiling HTML dynamically may seem unconventional. Why not opt for a directive template? If positioning content in another DOM level is the goal, consider utilizing a service for communication or implementing an isolate scope to streamline attribute binding.

A service could facilitate communication by storing a callback function triggered by the controller:

.service('modalService', [function() {
  var proxy = function(message) {
    proxy.callback(message);
  };
  proxy.callback = function() {};
  return proxy;
}])

By injecting this into both dialog and trigger controllers, seamless communication between them becomes possible. The modal dialog should replace the callback with its specific function. Refer to another demo for illustration.

Answer №2

I have a feeling that the issue lies in the conversion process, but I'm unable to store the "value" in a static variable within the main $scope. I need to access this "value" in order to invoke a modal window with generic functionality that relies on functions stored within it. That's why I opted to pass the "value" as an attribute. Is there another way to store the "value" along with its functions in the view or pass it directly to the directive controller?

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

JSON Response Handler

Here is the coding structure I am currently utilizing: func extractData(){ URLSession.shared.dataTask(with:apiURL!, completionHandler: {(data, response, error) in guard let data = data, error == nil else { return } do { ...

disable the form submission function in dropzone when buttons are clicked

Dropzone is being utilized on my page in the following manner alongside other input types such as text and select dropdowns: <form name="somename" method="post" action="/gotoURL" form="role"> // Other form elements here <div id="dropare ...

Conceal a Component within an Embedded Frame

Hey there! I've been attempting to hide a header within an iframe, but it seems like my code isn't doing the trick. Could someone take a look and help me diagnose why the header is still visible? Thanks in advance! <iframe id="booking_iframe" ...

Express app: the ideal location to implement a closed-loop temperature control system

I am relatively new to working with express.js, having only created some basic client/server apps in the past. Currently, I am looking to develop a temperature controller using a PID component. However, I am struggling to grasp the architecture of express ...

Updating state in React is not possible

I am having trouble updating my state (specifically with setCoords). The API request is returning a 200 status code and the elements I need are present: https://i.stack.imgur.com/a8QzN.png Below is the code I am working with: const App = () => { co ...

Directive that accesses an element and adds an event listener

I'm in need of developing an attribute directive using Angular 1.5.5 that will restrict inputs based on the keypress event of a text box. The desired output should be like this: <input type="number" name="age" id="age" restrict-char="['e&apos ...

javascript game for reversing an array

in case(po==true){ snake_array.reverse(); var i=0; var c=snake_array[i]; //drawing the head draw_head(c.x,c.y); for(i=1;i<snake_array.length;i++){ //drawing the body var c=snake_arr ...

Convert the value of a Javascript variable into a PHP variable

I am feeling confused about how to pass JavaScript variables to PHP variables. Currently, I have a PHP session named example_survey and three buttons with jQuery attributes. When a button is clicked, it triggers a jQuery click event and passes the attribut ...

Persist a SQL entity to a document with the help of Node.js

I am looking for a way to store the data from the rows object either in a file or as a JSON file. app.get('/getposts', (req, res) => { mysqlConnection.query('Select * from posts', (err, rows, fields) => { if (!err) console.l ...

What is the best way to expand the width of a table cell in a React + Material project?

Currently, I am utilizing material UI in conjunction with React to display my data in a table format. Within the table, there are specific titles such as "GENERAL_INFORMATION" and "INFORMATION" that I intend to center align. However, I have encountered an ...

Ways to implement a setTimeout function to return to the initial div element?

I have a unique setup on my webpage with three divs. The first div features an html5 video, the second div contains buttons for interaction, and the third div acts as a thank you page that loops back to the beginning like a photo slide. I have shared my co ...

I am utilizing jQuery's AJAX function with a datatype of HTML to extract a specific portion of the incoming data

This is the JavaScript function I am working with: function getCountryRegions() { var postData = "id="+$("#selectedCountryId").val(); $.ajax({ url:"/region", data: postData, dataType:"html", type:"POST", ...

Having difficulty displaying elements from two arrays at particular intervals

I am currently working with two arrays that have the same number of items in each. My goal is to print these items in intervals within the console. The desired output would look something like this: 1 Bruce Wayne 45 Then, after a one-second interval, it s ...

Is there a way to modify the CSS or add custom styling within an iframe form?

Currently I am working on the following page: , where an embedded javascript form called infusionsoft (iframe form) needs to be made responsive at the request of my client. I'm wondering if there is a way to override the css or inject custom styles i ...

The issue of background and footer distortion arises in PhoneGap when the keyboard is opened

Currently, I am experiencing screen problems with phonegap. The issue arises when a keyboard is opened, causing the back button at the bottom of the page to move above the keyboard and resulting in the background image appearing shorter. How can this be re ...

Struggle encountered while incorporating PayPal into my project

Recently, I encountered an issue while trying to integrate the PayPal-node-SDK into my project for a Pay with PayPal option. The error message I received was: XMLHttpRequest cannot load https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&a ...

Exploring how to access properties of objects in javascript

As a novice on this platform, I'm uncertain if the title may be deceiving, but I have a question regarding the following scenario: var someObject ={} someObject.info= { name: "value" }; How can I acce ...

Struggling to update the color of my SpeedDial component in MUI

I'm having trouble changing the color of my speed dial button. The makeStyle function has been working fine for everything else. Any suggestions? import React, {useContext} from 'react'; import {AppBar, Box, Button, Container, makeStyles, To ...

Exploring the contrasts in values within the ng-repeat directive of AngularJS

I am currently working with a JSON object that contains information about various clients, including the payments made over different date ranges within each month. My goal is to loop through this list of customers and display a table for each customer, hi ...

Changing Meteor Template to a Node.js/AngularJS Conversion

My current website is built with Meteor using templates structured like this: <body> {{>section1}} {{>section2}} {{>section3}} </body> <template name="section1"> <h1>This is Section 1</h1> </template> ...