Constructing a form by employing the directive approach to incorporate various input fields

My goal is to create input fields that capture information when the submit button is clicked using the directive method. These values will then be passed as arguments to a function. However, my current code is not functioning as expected.

<!DOCTYPE html>
<html>
<head>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
     <title>Random Network</title>

</head>
<body>
     <h1 class="title">Simulating a network</h1>
     <div ng-app="myApp">
     </div>
     <script type="text/javascript"> 
     var app = angular.module("myApp", []);
     app.directive('networkInputs', function() {
        return {
             restrict: 'E',
             scope: {},
             template: 

           '<h3 >Initialize new parameters for generating a network </h3>'+
                 '<form ng-submit="submit()" class="form-inline" ng-controller="MainCtrl">'+
                   '<div class="form-group">'+
                      '<label>Number of nodes:</label>'+
                      '<input type="number" class="form-control" ng-model="networkInputs.N" ng-required="true">'+
                   '</div>'+
                   '<div class="form-group">'+
                      '<label>Number of edges of a new node:</label>'+
                       '<input type="number" class="form-control" ng-model="networkInputs.m" ng-required="true">'+
                   '</div>'+
                   '<div class="form-group">'+
                      '<label>Minority:</label>'+
                      '<input type="number" class="form-control" ng-model="networkInputs.minority" ng-required="true">'+
                   '</div>'+
                   '<div class="form-group">'+
                       '<label>h<sub>ab</sub>:</label>'+
                       '<input type="number" class="form-control" ng-model="networkInputs.hAB" ng-required="true">'+
                   '</div>'+
                   '<div class="form-group">'+
                       '<label>h<sub>ba</sub>:</label>'+
                       '<input type="number" class="form-control" ng-model="networkInputs.hBA" ng-required="true">'+
                   '</div>'+
               '</form>'+
            '<button style="color:black; margin: 1rem 4rem;" ng-click="submit()">Generate</button>';
     });
        app.service('param', function() {
            var param = this;
            param = [];
        });
        app.controller("MainCtrl",  ['$scope','param',function($scope, param) {

            $scope.networkInputs = {};


            $scope.submit = function() {
                var dataObject = {
                    N: $scope.networkInputs.N,
                    m: $scope.networkInputs.m,
                    minority: $scope.networkInputs.minority,
                    hAB: $scope.networkInputs.hAB,
                    hBA: $scope.networkInputs.hBA
                };
                console.log($scope);
                param.push(dataObject);
                $scope.networkInputs = {};
            }
        }]);


</script>

</body>

</html>

I am looking to utilize the values stored in the param object as input arguments for another function. Any guidance on how to achieve this would be greatly appreciated.

Answer №1

After reviewing your directive, here are some suggestions:

1) It is recommended to embed the directive within a tag in your app for proper functionality;

2) Utilize bindings for enhanced input and output management;

3) To enable form submission using ngSubmit, ensure that the button is enclosed within the form tag with a type='submit' attribute;

4) Avoid using ngController inside the template of your directive. Instead, consider utilizing the controller or link property for integrating a controller.

Below is an illustrative example defining and implementing the networkInputs directive:

var app = angular.module("myApp", [])
.directive('networkInputs', function() {
  return {
       restrict: 'E',
       scope: {
          inputs: '<',
          submit: '&'
       },
       template: 
     '<h3 >Initialise new parameters to generate a network </h3>'+
           '<form ng-submit="submit({inputs: inputs})" class="form-inline">'+
             '<div class="form-group">'+
                '<label>Number of nodes:</label>'+
                '<input type="number" class="form-control" ng-model="inputs.N" ng-required="true">'+
             '</div>'+
             '<div class="form-group">'+
                '<label>Number of edges of a new node:</label>'+
                 '<input type="number" class="form-control" ng-model="inputs.m" ng-required="true">'+
             '</div>'+
             '<div class="form-group">'+
                '<label>Minority:</label>'+
                '<input type="number" class="form-control" ng-model="inputs.minority" ng-required="true">'+
             '</div>'+
             '<div class="form-group">'+
                 '<label>h<sub>ab</sub>:</label>'+
                 '<input type="number" class="form-control" ng-model="inputs.hAB" ng-required="true">'+
             '</div>'+
             '<div class="form-group">'+
                 '<label>h<sub>ba</sub>:</label>'+
                 '<input type="number" class="form-control" ng-model="inputs.hBA" ng-required="true">'+
             '</div>'+
             '<button style="color:black; margin: 1rem 4rem;" type="submit">Generate</button>' +
         '</form>'};
})
.controller("MainCtrl",  ['$scope',function($scope) {

      $scope.networkInputs = {};
      
      $scope.submit = function(inputs) {
          // Perform necessary operations with the provided data within the controller
          var dataObject = {
              N: inputs.N,
              m: inputs.m,
              minority: inputs.minority,
              hAB: inputs.hAB,
              hBA: inputs.hBA
          };
          // Log the data (can be customized as needed)
          console.log(dataObject); 
          // Clear the form after submission
          $scope.networkInputs = {};
      }
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body ng-app="myApp">
     <h1 class="title">Simulating a network</h1>
     <div ng-controller="MainCtrl">
        <network-inputs inputs="networkInputs" submit="submit(inputs)"></network-inputs>
     </div>
</body>

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

Enhance Your Angular SPAs with Automated Accessibility Testing Tools

Has anyone had success using an automated accessibility testing tool specifically designed for Angular Single Page Applications (SPA)? I experimented with pa11y, but it was not providing consistent results. I'm curious if there are other tools simila ...

What are the benefits of sticking with Express versus transitioning to a combination of JavaScript and HTML?

Recently, I've been developing a web application that involves taking user input to make modifications to files on the server side. The main logic for this project is built in node.js and operates via command line, with the rest of the site being deve ...

How can I customize the visibility toggles for the password input field in Angular Material?

Currently immersed in the Angular 15 migration process... Today, I encountered an issue with a password input that displays two eyes the first time something is entered in the field. The HTML code for this is as follows: <mat-form-field appearance=&qu ...

Can an HTML DIV be resized along with its contents?

Is it possible to scale a container with animated elements inside to fit the browser window, or do you have to adjust each child element individually? ...

Setting MUI input value within a loop using an array value in React JS: A step-by-step guide

Recently, I created a React js demo using React MUI. To handle inputs, I created a separate component called InputText.js for each input field. The issue I encountered is when I tried to use this component to display multiple education fields stored in an ...

AngularJS: Changing color property using toggle when a CSS class is modified

After starting to learn AngularJS, I have been able to find many helpful answers on this forum. However, there is one particular issue that has been causing me frustration. My goal is to dynamically change the color property of an element only when it has ...

Ways to determine if an image has a designated width/height using JavaScript (jQuery)

Similar Question: How can I retrieve the height and width of an image using JavaScript? Typically, we can determine the image width using $('img').width() or $('img').css('width') when a width is specified as shown below ...

Switch back and forth between two different function loops by clicking

I have implemented two sets of functions that animate an SVG: one set runs in a vertical loop (Rightscale.verticalUp and Rightscale.verticalDown) and the other in a horizontal loop (Rightscale.horizontalUp or Rightscale.horizontalDown). On clicking the SVG ...

I am encountering an issue with my function where I aim to prevent the creation of a node using duplicate coordinates

Trying to avoid creating a node with existing coordinates, I implemented a check in my code. The check is supposed to determine if there are any nodes with the same coordinates already present. However, it seems that the check is not working as expected an ...

Is it feasible to implement different themes besides 'light' and 'dark' in React Material UI?

Currently, I am developing a user interface (UI) using React in combination with Material UI (v5+). The documentation provides information on how to utilize the extendTheme function along with CssVarsProvider to incorporate MUI colors into CSS. It also men ...

The disadvantages of manipulating DOM in controllers in AngularJS

Many experts advise against performing DOM manipulations in AngularJS Controllers, but it can be challenging to fully understand why this is considered a best practice. While sources mention issues with testing and the primary purpose of controllers for di ...

Show the output of a MySQL query on a modal, alert, or popup box within a webpage initiated by a search box, with the option to close the

Having worked in IT for 16 years, I am new to coding and seeking help on displaying search results from an input HTML box. I want the data from a MySQL database to be displayed in a modal, alert, or popup box with a closing "X" button. This database only c ...

"Proper Installation of Angular Project Dependencies: A Step-by-Step

Whenever I clone an Angular project with older versions that are missing the node_modules folder, and then run npm install to install all necessary dependencies, I end up receiving numerous warnings and errors related to version mismatches. Here are some ...

IE11 encounters an error labeled SCRIPT1010, signaling an expected Identifier when compiled

Lately, I've been encountering a strange issue in Vue.js. Here's the thing: my application runs smoothly on all browsers locally (yes, even IE 11). But when I compile it using npm run build and deploy it to my server (which essentially serves con ...

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

Passing a dynamic value to a modal in AngularJS: A guide to enhancing user interaction

I'm attempting to send dynamic parameters to a modal by clicking a button, but some values are not being captured correctly and returning empty. Below is the snippet of my modal: <div id="<%handler%>" class="modal fade"> <div clas ...

How can the error within a promise be captured when using resolve()?

Check out the code snippet below: userUpdate(req: Request, res: Response) { this.userTaskObj.userUpdate(req.params.id, req.body).then(() => { res.status(200).json({ status: 'OK', message: 'User updated', ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

Creating an AngularJS recursive tree that displays the path or depth of each node

My goal is to display a tree using AngularJS and include the full path for each node. Consider the following model: ... $scope.data = { nodes: [{ name: "Apple", nodes: [{ name: 'Mac', nodes: [{ ...

Ways to rejuvenate an Angular element

Last month, I was called in to rescue a website that was in chaos. After sorting out the major issues, I am now left with fixing some additional features. One of these tasks involves troubleshooting an angular code related to videos and quizzes on certain ...