Passing a parameter to an AngularJS directive, which triggers the opening of an ngDialog, and subsequently updating the value to reflect changes in the root scope

Struggling with a persistent issue here; Essentially, I have a directive that triggers an ngDialog to open. This directive should be able to receive a variable from the root scope. The directive contains a click event that opens an ngDialog which then uses the passed-in value to populate a textbox... but updates made in the textbox within the ngDialog are not reflecting back on the root scope.

The Challenge The variable being passed does not maintain its link to the rootscope. Updates in the ngDialog don't propagate back to the root scope and I suspect I've overlooked something fundamental. Any assistance would be greatly appreciated.

//HTML Snippet

<b>Instructions: </b>Click on the blue items to open ngDialog<br /><br />
<div ng-controller="MyCtrl">
    <b>Base $scope.variable1 = </b> {{variable1}}
    <span pass-object passed-object="variable1"></span><br />
    <b>Base $scope.variable2 = </b> {{variable2}}
    <span pass-object passed-object="variable2"></span><br />
    <b>Base $scope.variable3 = </b> {{variable3}}
    <span pass-object passed-object="variable3"></span><br />
</div>

//JavaScript Code

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

myApp.controller('MyCtrl', function ($scope) {
    //Defining 3 scope variables
    $scope.variable1 = "value 1";
    $scope.variable2 = "value 2";
    $scope.variable3 = "value 3";
});

//Creating a directive for opening an ngDialog that can accept and update a scope variable within it
myApp.directive('passObject', ['ngDialog', function(ngDialog) {
    return {
        restrict: 'A',
        scope: { passedObject: '=' },
        template: "<div class='directive'>This directive's received value is = {{passedObject}}!</div>",
        link: function($scope, element){
            element.on('click',function(){
                ngDialog.open({
                    template: '<div>I want changes in this textbox to reflect in root scope:<br /><br />' + 
                              '<input type="text" ng-model="passedObject"/></div>',
                    plain: true,
                    scope: $scope,
                    controller: ['$scope', function($scope){
                        $scope.$watch('passedObject', function(passedObject){
                            //Need to figure out why changes at this level aren't propagating upwards
                            alert('updated with: ' + passedObject);
                            $scope.$apply();
                        });
                    }]
                })
            });
        }
    };
}]);

//Check out the Fiddle for reference

http://jsfiddle.net/Egli/od8a2hL0/

//Many Thanks :D

We appreciate any help offered

Answer №1

When you encounter the error message "the console says $digest already in progress, just remove the $scope.$apply();"

Here is a helpful link: http://jsfiddle.net/usmoetyd/

To avoid this issue, it is recommended to use objects instead of primitive types in your AngularJS controller:

myApp.controller('MyCtrl', function ($scope) {
    // Let's say I have 3 scope variables
    $scope.variable1 =  { value : "value 1" };
    $scope.variable2 =  { value: "value 2" };
    $scope.variable3 =  { value: "value 3" };
});


// If you need to pass a scope variable into a directive and update it from within ngDialog, consider using an object.
myApp.directive('passObject', ['ngDialog', function(ngDialog) {
    return {
        restrict: 'A',
        scope: { passedObject: '=' },
        template: "<div class='directive'>This is the value passed into this directive = {{passedObject.value}}!</div>",
        link: function($scope, element){             

            element.on('click',function(){             
                ngDialog.open({
                    template: '<div>By updating I need it to reflect in the root scope:<br /><br />' + 
                              '<input type="text" ng-model="passedObject.value"/></div>',
                    plain: true,
                    scope: $scope,
                    controller: ['$scope', function($scope){
                        $scope.$watch('passedObject', function(passedObject){
                            // Make sure to update the parent scope when changing the object at this level
                            console.log(passedObject);                                
                        });
                    }]
                })

            });
        }
    };
}]);

For more examples, visit: http://jsfiddle.net/jyk6Lbwe/1/

If you want to dive deeper into AngularJS prototypal inheritance, check out this informative Stack Overflow thread: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

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

JavaScript - The function will not execute any code inside its body

When I try to call my constructor function, it stops at the function definition in the debugger and never reaches the actual function body. Is there a common reason for this issue that I might be missing? Here is an example of the code: myconstructor.js ...

Make sure to include the onBlur and sx props when passing them through the slotsProp of the MUI DatePicker

This DatePicker component is using MUI DatePicker v6. /* eslint-disable no-unused-vars */ // @ts-nocheck import * as React from 'react'; import { Controller } from 'react-hook-form'; import TextField from '@mui/material/TextField&a ...

Tips for retrieving JSON data from an AJAX call and displaying it pre-filled in an input field

Here is the code snippet I used to receive a response in JSON format, but when I try to display the response using alert(response.Subject);, it shows as "undefined". HTML: <input type="text" id="subject" value='Subject'> Javascript: $.a ...

What causes the namespace to shift when utilizing npm for installing a library?

I've been attempting to integrate whammy.js into a project. The initial line in the source code is window.Whammy = (function(){ yet, after running npm i and inspecting node_modules, I discovered global.Whammy = (function(){ https://github.com/anti ...

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...

What steps should I take to make jQuery compatible with a Greasemonkey 0.8 script on Firefox 2, without internet access on the computer?

Currently using Firefox 2.0.0.11, Greasemonkey 0.8.x, and the latest version of jQuery (1.3.2) that is compatible with Greasemonkey 0.8. Attempting to load this Userscript: // ==UserScript== // @name TEST // @include * // @require jquery. ...

Executing code only after the completion of the .ajax function (outside of the .ajax function)

Working with an API, I successfully implemented the .ajax function but now need to access the data outside of that function. Attempting to use jQuery's .done function for this purpose has proved unsuccessful so far. Despite trying different solutions ...

Troubleshooting a Malfunctioning AJAX Request in a WordPress Plugin

After carefully reviewing this post about a jQuery Ajax call in a Wordpress plugin page, I found that it closely matched my current issue. My basic Wordpress plugin is designed to offer a specific membership form that passes payment details to PayPal for p ...

Assigning index values to child rows in AngularJS: a step by step guide

One of my requirements involves assigning index values to child rows. The structure includes group rows with child rows underneath. Currently, I am using ng-repeat along with $index for the children as shown below: HTML code: <table ng-repeat="nod ...

Is there a way to validate form elements in HTML prior to submitting the form?

In my form, I am utilizing PHP for validation and processing, but I am interested in verifying elements as they are being filled out. Is there a way to check the current value of an element before the form is submitted? ...

ng-class in Angular seems to be functioning properly on <td> elements, but is not

When using this HTML inside an ng-repeat, there is a difference in behavior: This part works fine: <tr> <td ng-class="info.lastInMonth">{{ info.date_formatted }}</td> ... But this section does not work as expected: <tr ng ...

What is the best way to trigger a function once another one has finished executing?

After opening the modal, I am creating some functions. The RefreshBirths() function requires the motherId and fatherId which are obtained from the getDictionaryMother() and getDictionaryFather() functions (these display my mothers and fathers on the page s ...

Discover Vue3's efficient event handling feature that allows you to easily listen to events from dynamically generated child components

I am dynamically creating a Vue component and need to listen to the event it emits. While I know that you can use @eventName in the markup, my component is being created using createApp. const div = document.createElement('div'); this.$refs.logi ...

Using JQuery to visually enhance the menu selection by displaying an image and altering the background color upon hovering

Hello fellow JQuery/Javascript beginners! I recently put together a menu and wanted to add some interactive elements. Specifically, I want the background color to change when a user hovers over an item (simple enough with CSS), but I also want to include a ...

Incorporate child routes within a React component

I've been attempting to include <route> in a component within a routers component, but it doesn't seem to be working. Can anyone provide some assistance? My login page currently has a form and I'd like to switch that out with routes. ...

Encountering Webpack issues following the transition to Next 13

Since updating Next to version 13, we've encountered issues with our application not building properly. It appears that webpack is having trouble with imports, exports, and potentially typescript. ../../libs/queries/src/lib/groq/searchFaq.ts Module pa ...

proper integration of socket.io

I have been experimenting with socket io for my project to display online friends, and I have noticed an issue that seems strange to me. Every time the page is rerendered (whether due to a user changing their profile information or sending a friend request ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

Prevent methods from being called in a Typescript class after they have already

I encountered a scenario where I need to exclude certain methods from the return type of a class method once they have been called. Consider a class named Setup with methods step1, step2, and step3. class Setup { step1() { return this; } ...

Refreshing Data on Vuetify Range Slider

My goal is to update the value as the slider position changes. [codepen]https://codepen.io/JakeHenshall/pen/WLezNg <div id="app"> <v-app id="inspire"> <v-card flat color="transparent"> <v-subheader>Tick labels</v-subheade ...