Sharing scope variables between multiple dynamically created directives

Find my Plunkr example here: http://plnkr.co/edit/9LcYbn1468miu5McgPqR?p=preview

I successfully added the form to the variable inside the options parameter, but I am looking to bind it to a different location outside of the options parameter.

I have a custom panel directive that generates a panel. Within the panel options, I can specify a directive for the panel to dynamically invoke:

(function (ng, app)
{

    "use strict";

    app.directive(
        "panel",

        function ($compile)
        {
            return {
                scope: {
                    options: '=',
                },
                link: function(scope, element, attrs)
                {
                    el = angular.element('<' + scope.options.Directive + ' options=\'' + JSON.stringify(scope.options.DirectiveOptions) + '\' ' + additionalOptionsString + '></>');

                    element.find(".panel-body").append(el);

                    $compile(el)(scope);
                },
                templateUrl: function (elem, attr)
                {
                    return '/Panel.html';
                },

            }
        });
})(angular, app);

The functionality works well and the directive is dynamically instantiated as desired. However, I have another directive within another panel, and inside that is yet another directive. Both directives have isolated scopes. The structure is as follows:

Panel
   Directive
      Panel
         OtherDirective

I aim to pass an additional parameter option to the "Other Directive" so that the data in "Other Directive" is accessible to "Directive." Currently, the options are being hardcoded in the json format by the panel, which is not ideal. The additional scope variable ends up like this:

<OtherDirective options='{"hardCodedJson": "Value"} ' scopeVariableToBind='VariableInDirective'></OtherDirective> 

However, the variable 'VariableInDirective' is not being bound by OtherDirective. Below is the code for these two directives:

    (function (ng, app)
    {

        "use strict";

        app.directive(
            "directive",

            function ()
            {
                return {
                    scope: {
                        options: '=',
                    },
                    controller: function ($scope)
                    {
                        $scope.Comment;

                        $scope.OtherDirectiveOptions=
                        {
                            showcreatebutton: false,

                        };

                        $scope.OtherDirectivePanelOptions = {
                            Id: $scope.options.Id,
                            Title: $scope.options.Title + " Comment",
                            Directive: "otherdirective",
                            DirectiveOptions: $scope.OtherDirectiveOptions,
                            test: true,
                            AdditionalOptions: { "scopevariabletobindto": "VariableInThisScope" }
                        }

                        $scope.test = function ()
                        {
                            debugger;
                        }
                    },
                    templateUrl: function (elem, attr)
                    {
                        return '/Directive.html';
                    },
                }
            });
    })(angular, App);

Other Directive has a form that I want to bind to a scope variable from the above directive. I need to chain the variables going up the nested controls in order to access them hierarchically. Here is the code for Other Directive:

   (function (ng, app)
    {

        "use strict";

        app.directive(
            "otherdirective",

            function ($compile)
            {
                return {
                    scope: {
                        options: '=',
                        scopevariabletobindto: '=',
                    },

                    controller: function ($scope, $element)
                    {

                        $scope.id = $element.parent()[0].id;
                        $scope.form = {};

                    templateUrl: function (elem, attr)
                    {
                        return '/OtherDirective.html';
                    },
                }
            });
    })(angular, app);

Despite my efforts, I am unable to bind the form to the scope variable passed in as 'scopevariabletobindto.' Any insights on why this binding is not functioning?

Edit:

I have discovered that passing the form property as a function using the & symbol resolves the issue.

Answer №1

The issue at hand pertains to Angular naming conventions. When declaring attributes, it is important to use 'kebap-case', which involves concatenating words with a hyphen. However, these attributes are then translated internally to 'camelCase'. To ensure consistency, it is advisable to convert attribute names from camel to kebap before incorporating them into the HTML tag.

For instance, avoid the following:

# HTML
<div scopeVariableToBeDefined=".."></div>

# JS
... 
scope: {
   scopeVariableToBeDefined: "="
}

Instead, adhere to the recommended practice:

# HTML
<div scope-variable-to-be-defined=".."></div>

# JS
... 
scope: {
   scopeVariableToBeDefined: "="
}

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

What does drizzle.config.ts serve?

I've been working on setting up a project with Drizzle + Next.js + Vercel for my serverless backend. To utilize the ORM API of Drizzle, I reference my database in the following way: import { drizzle } from "drizzle-orm/vercel-postgres"; impo ...

rely on a fresh event starting at one

Despite my limited knowledge in javascript, I managed to create a simple js calendar that I am quite proud of. However, I have been facing a challenge for the past few days. You can view my calendar here: https://jsfiddle.net/ck3nsemz/ The issue I'm ...

Beautify JSON data display

My JSON object is displaying differently when I alert it: https://i.stack.imgur.com/lwNIJ.png I would like it to show like this instead: https://i.stack.imgur.com/cVakX.png function getEmployeeNameById(id){ return staffArray.find(item => item. ...

Navigating Angular.js: finding my way to the endpoint paths

Despite my best efforts and extensive research, I find myself in need of assistance! I have a web application that utilizes node and express on the server side, with Angular on the client side. My issue lies with angular routing. IMPORTANT DETAILS My cur ...

JavaScript inquiry

How do you typically utilize JavaScript in your projects? I often use it for form validation, creating dropdown menus, and more. Do you have any unique ways of using JavaScript? Personally, I find jQuery to be a superior tool in certain situations... ...

Transform a flat 2D shape into a dynamic 3D projection using d3.js, then customize the height based on the specific value from ANG

Currently, I am utilizing d3.js version 6 to generate a 3D representation of the 2D chart shown below. Within this circle are numerous squares, each colored based on its assigned value. The intensity of the color increases with higher values. https://i.ss ...

Angular.js Routeprovider for "landing page"

Recently completed an amazing angular js app. Now, I'm looking to create a welcome page for users to start the application from. However, I'm having trouble figuring out how to implement this in my routeprovider since my index.html contains both ...

Is it wise to question the validity of req.body in express.js?

https://expressjs.com/en/4x/api.html mentions It is crucial to validate all properties and values in the req.body object as they are derived from user input. Any operation performed on this object should be validated to prevent security risks. For instan ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

After submitting the form, React checkboxes fail to reset their state

Being a relative newcomer to React, I embarked on creating a skincare app as a project to enhance my understanding. In designing the app, I incorporated a form for product registration which includes checkboxes. My current dilemma revolves around clearing ...

Struggling to implement JQuery code in a Next.js application

I'm having trouble getting my tracking code to work in Next.js. <Script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments) } gtag('js', new Date()) ...

The push() function is triggering an error where db._checkNotDeleted is referenced incorrectly as a

I'm attempting to save an object in the database. Here's the code snippet I've been using: app.post('/newOrderWithObject', (req, res) => { var msg = {"name":"Harry"}; push(ref(db,"test/orders&qu ...

resolved promise's then method was not invoked

Attempting to stub a method using sinon, jasmine, and $q. Wanting the method to return fake data. An issue arises where the defined then statement is never executed, and the reason remains unknown. The stub is invoked The console log displays Steven Stu ...

Npm publish seems to be stuck without generating any output

I'm having trouble trying to publish a package that I created. The files can be found at this Github Repo. When I run the command npm publish, it just seems to hang without any errors or output. I've attempted logging in using npm login and npm a ...

Changing the color of a Highcharts series bar according to its value

Playing around with Highcharts in this plunker has led me to wonder if it's possible to dynamically set the color of a bar based on its value. In my current setup, I have 5 bars that change values between 0 and 100 at intervals. I'd like the colo ...

Divide the string by spaces

One of the challenges I am facing involves a textarea where users can input messages. The goal is to split the message into an array of words after detecting an '@' symbol, and then search for specific words in that array such as @person1 and @pe ...

Deactivate the typeahead function in the Angular controller based on the user's preference

Is there a way to disable Angular's typeahead feature when a user has a specific checkbox checked in the settings menu (with id = searchSuggestions)? The code provided below seems to work only on a fresh page reload, but not during an active session. ...

When attempting to display a sub view in Express, a 404 error is encountered

I am currently working with express and jade to display a web page. My intention is to render the page using this format 'http://127.0.0.1:5000/services/landfreight' but I keep encountering a 404 error. router.get('/service/landfreight' ...

The regular expression used for validating domains does not function properly in the Safari browser

I am struggling with a JavaScript regular expression error that Safari is giving me. I am trying to validate a domain, but for some reason, this specific part (?<!-) is causing the issue because the domain name should not end with a hyphen. ^((?!-)[A-Z ...

Error encountered while attempting to build Ionic 5 using the --prod flag: The property 'translate' does not exist on the specified type

I encountered an error while building my Ionic 5 project with the --prod flag. The error message I received is as follows: Error: src/app/pages/edit-profile/edit-profile.page.html(8,142): Property 'translate' does not exist on type 'EditProf ...