The functionality of the function from the controller does not seem to be effective within the Angular directive

Hey everyone! I created a form using dynamic data and in the future, I will need to compile this form, fill it with data, and submit it. Here is how I built the form:

<div>
<form name="pageForm">
<div>
<div class="form-group" ng-repeat="item in formStructure.form_data"
dynamic="item" templates="templates"></div>
</div>
</form>
</div>

I have templates for different parts/inputs of the forms stored in the JavaScript code like this:

$scope.templates.checkbox = '<label><input ng-required="item.conf.required"' + 
'ng-model="formData[item.conf.name]" type="checkbox" > {{item.conf.title}} </label>';

And I am using the following directive:

function dynamic ($compile) {
    return {
        restrict: 'A',
        replace: true,
        scope: { dynamic: '=dynamic',
            templates: '=templates',
            eventlstn: '&'
        },
        link: function postLink(scope, ele, attrs) {
            scope.$watch( 'dynamic' , function(html){
                scope.item = html;
                ele.html(scope.templates[html.type]);
                $compile(ele.contents())(scope);
            });
        }
    };
}

However, after creating the form, clicking on elements with ng-click="someFunctionINController()" doesn't trigger any actions.

In addition, I'm unable to access form data using ng-model in my HTML.

Check out the plunker here!

Answer №1

After much trial and error, I have finally found a solution: I made some changes to the directive:

function dynamic ($compile) {
    return {
        restrict: 'AE',
        replace: true,
        scope: false,
        link: function postLink(scope, ele, attrs) {
            scope.$watch( 'dynamic' , function(){
                ele.html(scope.templates[scope.item.type]);
                $compile(ele.contents())(scope);
            });
        }
    };
}

By using scope: false in the directive, it now shares the same scope with the controller. Thank you, Grundy, for your assistance.

I plan to make this solution (Enhanced Drag'n'Drop form builder) public in the future, hoping it can benefit others as well.

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

In Javascript, you can throw, instantiate a new Error(), and populate its custom properties all in a single line of code

Can all of this be done in a single line? if (!user) { const error = new Error('Invalid user.') error.data = someObject error.code = 401 throw error } Here's an example (with data and code properties populated) if (!user) th ...

JavaScript code that iterates through all files in a designated folder and its subfolders using a for loop

I am looking to combine two JavaScript scripts into one, but I'm not sure how to do it. The first script uploads files from a specified folder to VirusTotal for scanning and returns the scan result. The second script lists all files in the specified ...

Failed to load CSS file in nodeJS application

I followed a tutorial to create a backend app using nodeJS and Express. My MongoDB connection with Mongoose is working fine. However, I am facing issues when trying to add a simple front-end using html/ejs/css. The endpoints are loading on localhost but on ...

Getting stuck trying to fetch the queryset from the server and adding it to the select options using AJAX

I have managed to successfully send the value of the input field with the id datepicker to the server. In the view, I am able to filter the time slots based on the selected date. However, I am facing a challenge in sending this queryset back to the browse ...

Using Reactjs to create a custom content scroller in jQuery with a Reactjs twist

I am attempting to implement the Jquery custom scrollbar plugin here in my React project. Below is a snippet of my code: import $ from "jquery"; import mCustomScrollbar from 'malihu-custom-scrollbar-plugin'; ..... componentDidMount: function() ...

What is the process of linking an alert message to the controller?

Hey everyone, I've been playing around with a simple commenting app built with AngularJS and I'm facing a challenge in displaying an alert message when a user enters an empty string into the input field. Below is the HTML view with ng-show logic ...

JQuery If Statement always outputs a consistent number regardless of the input provided

I'm facing an issue with my HTML form and JQuery code that is supposed to calculate a figure. The problem I am encountering is that the if statement always returns the same number, regardless of the input: $(document).ready(function() { ...

Using Mocha with the --watch flag enabled causes issues with ES6 modules and results in error messages

I've been attempting to configure Mocha to automatically monitor for changes in my files using the --watch flag. I have defined two scripts in package.json as follows: "test": "mocha", "test:watch": "mocha --watch ./test ./game_logic" When I run ...

Is it possible to incorporate dynamic variables into the directives of a nested loop? Plus, thoughts on how to properly declare variables in a node.js environment

Question Explanation (Zamka): <----------------------------------------------------------------------------------------------------------> Input Example: 100 500 12 1st Line: represents the left bound (L) 2nd Line: represents the right bound ...

Retrieving historical data from a MySQL database to display in a div element

My main page features a button that opens a popup. Upon closing the popup, a script is triggered to call a PHP file for selecting data from the database. This selected data is then appended to a specific div within the main page: if (win.closed !== false ...

React - Stopping the Submit Action

Recently, I have been delving into React development. In my exploration, I have incorporated the Reactstrap framework into my project. However, I have encountered an issue where the HTML form submits when a button is clicked. Is there a way to prevent this ...

Transfer a csv file from a static webpage to an S3 bucket

Looking to create a webpage for uploading csv files to an S3 bucket? I recently followed a tutorial on the AWS website that might be helpful. Check it out here. I made some modifications to accept filename parameters in my method, and everything seems to ...

Are there alternative methods for retrieving data in Vue Hacker News besides using prefetching?

I am currently developing a Vue single page application with server side rendering using Vue SSR. As per the official documentation, data in components will be prefetched server-side and stored in a Vuex store. This process seems quite intricate. Hence, ...

Tips for resolving circular dependencies: When Vuex requires JS modules that are dependent on Vuex

I am facing a challenge with my Vuex store, as it imports the notifications.js module that requires access to Vuex.store.state. How can I resolve this issue? Currently, I am passing store.state as a prop to address the circular dependency. Is there a more ...

The console is showing messages before the task is completed

When using console.log to write detailed messages about the current task expected to be performed by Protractor, I noticed that these messages are appearing on the console before the actual task is executed in the browser. An example of this is: it(' ...

Having Difficulty Configuring Async Request Outcome

I'm struggling to access the outcome of an asynchronous request made to an rss feed. After reading a post on How do I return the response from an asynchronous call?, which recommended using Promises, I tried implementing one. However, even though the ...

Fade away effect for the session flash message

How can I implement a flash message session for Laravel? I want the flash messages to be displayed when I add or delete items, but is there a way to make them fade out? In my view file, I have included the following code: <script> $(documen ...

How can I retrieve the second letter in Materialize CSS FormSelect by using the keyboard?

On my website that utilizes materializeCSS and Jquery, I have encountered an issue with a select box containing numerous options. Typically, when using a select box, I can press a letter multiple times to cycle through options starting with that letter. ...

Storing data as a JSON string in a JavaScript object and saving it to

Have you ever wondered why the cart object is saved as "cart" in the local storage instead of being an actual object? This discrepancy is causing the cart not to display correctly. This issue arose after deploying the website on Vercel. Storing "cart" as ...

Is there a way to apply -webkit-line-clamp to this JavaScript content using CSS?

i have a random-posts script for my blogger website <div class="noop-random-posts"><script type="text/javascript"> var randarray = new Array(); var l=0; var flag; var numofpost=10; function nooprandomposts(json){ var total = ...