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

The event broadcasting from the $rootScope in the controller and the event listening in the directive's $scope are not functioning properly in the 1

Could use some help with calling $rootScope.broadcast from my controller and listening to it in the directive. Controller: function startFunction(){ $rootScope.$broadcast('sharingFn'); } startFunction(); Directive: $scope.$on('shari ...

Display a video modal upon page load, allowing users the option to click a button to reopen the modal

Looking for a way to make a video modal automatically open on page load and allow users to reopen it by clicking a button? Here's a snippet of code that might help you achieve that: HTML <html> <head> <link rel="stylesheet ...

Having trouble with res.render() when making an axios request?

I am encountering an issue with my axios requests. I have two requests set up: one to retrieve data from the API and another to send this data to a view route. const response = await axios({ method: 'POST', url: 'http:// ...

What is the method for adding line breaks to a JSON file?

I've been developing a Discord bot and I'm currently storing currency values in a json file. The functionality is working smoothly, but the issue I'm facing is that it's adding them to the json file in a single line which makes it diffi ...

Could we confirm if this straightforward string is considered valid JSON data?

There are numerous intricate questions on Stack Overflow about whether a complex structure is considered valid JSON. However, what about something much simpler? "12345" Would the provided code snippet be considered valid JSON? ...

Customized template based on user's dropdown choice

Looking to implement a dynamic template that changes based on user selection. For example, when a dropdown option is chosen, another HTML template should be loaded. I want to approach this in an organized and modular manner, with controllers that can be ...

A useful method to generate dynamic and random interval values for each loop of setInterval in NodeJs

I am trying to implement a feature where a function in nodeJS triggers another function at random intervals within a specified range. Each time the loop occurs, I want the interval value to be different and randomly generated between 3 and 5 seconds. bot ...

The stacking order of elements is not affected by the z-index property when using absolute positioning

I have developed a unique custom toggle switch component with the following structure: <template> <div> <label class="switch"> <input type="checkbox" :checked="value" @c ...

Is it possible to dynamically load records in real time with the help of PHP and jQuery?

I developed a custom system using PHP that allows users to post status messages, similar to a microblog. The system utilizes a database table structured like this: posts_mst ------------------ post_id_pk post_title post_content date_added Initially, I su ...

Develop a dynamic button using JavaScript to fetch information from an array

I'm struggling with incorporating this button creation code into my HTML using JavaScript. The code for creating the button element in JS file looks like this: var numery = ['A','B','C']; var numer = document.createE ...

Sending the value of "username" between two components within Angular 2

I have a good understanding of nesting child components within parent components in Angular 2, but I'm a bit unclear on how to pass a single value from one component to another. In my scenario, I need to pass a username from a login component to a cha ...

What is the best way to make a drop down menu list appear when I click on the parent li, and then show the sub li using JavaScript?

I have a code that includes an image, HTML, and CSS code. Can anyone please tell me how I can set up a drop-down menu list to open the sub <li> elements when I click on a parent <li> using JavaScript? You can see the appearance of the code in t ...

The paragraph tag remains unchanged

I am currently working on developing a feature that saves high scores using local storage. The project I'm working on is a quiz application which displays the top 5 scores at the end, regardless of whether the quiz was completed or not. However, I&apo ...

Accessing the `this` element in ES6 after binding to the class

Is there a way to retrieve and interact with this element after applying the this class? For instance, when not using this: $(".button-open").click(function(event) { console.log(this); // <a href="#" class="button-open">Open</a> this. ...

You are unable to reference a member within the embed in discord.js v13

I created a system for logging join and leave events in my server. However, I encountered an issue where the member is not mentioned when the bot sends the embed in the channel. Here is a snippet of my code: client.on('guildMemberAdd', guildMemb ...

What is the best way to inform Angular2 RC1 about updates in the DOM?

Originally inspired by a discussion on Stack Overflow, this scenario presents a simpler use case. The issue at hand is how to inform Angular2 about externally added DOM elements that contain Angular directives. For example, adding a new button with a click ...

Issues with updating the style in Internet Explorer and Firefox using JavaScript are currently unresolved

I am facing an issue with my program where a name from an auto-complete is sent to a JavaScript function that dynamically creates a label with a button inside. Surprisingly, the DOM methods used to set style properties do not work in Firefox and IE 7, but ...

Generate several sliders using JQuery effortlessly

As I was attempting to create multiple sliders with JQuery in a more automated fashion using iteration, several questions arose (you can see a functional example below). Why does the first block of JQuery code work while the second block of JavaScript cod ...

The npm error message states: "Unable to locate the 'readable-stream' module."

Recently, I installed node js on my Windows 10 machine with version v4.4.2. However, whenever I attempt to run npm install or check npm version, it throws the following error message. Any assistance on this matter would be highly appreciated. Error: Canno ...

Troubleshooting: JSColor Is Failing to Function Properly in Volusion's

Recently, I've encountered some issues with the JSColor plugin () on the Volusion e-commerce platform. Despite having successfully used it before, getting it to load correctly seems to be a challenge. My current task involves working on a test produc ...