When utilizing ng-repeat and invoking the function in the HTML, the JSON array values fail to transfer to the HTML form

What I am trying to achieve:

https://i.sstatic.net/hbdbC.jpg

I am facing issues with getting the desired dynamic form output. The values are not being displayed and the data is not passing from the JavaScript file to the html form. I have even tried using the console, but it doesn't seem to work. Could someone help point out where I might be making a mistake? Here is the codepen link and relevant code:

http://codepen.io/anon/pen/YVzRmZ

<!DOCTYPE html>
<html ng-app="inputs">

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2a252c3e272a396521380b7a657f657a">[email protected]</a>" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl">

<div id="result" style="width:600px; text-transform: capitalize;" align="right">My_form</div>

<div ng-repeat="component in components">

<span ng-class="mylogic(component)">

</div>



var app = angular.module("inputs",[]);

app.controller("MainCtrl",function($scope){

$scope.components=[{
  'name':{
    'fname':'{"placeholder":"First Name","description":"Enter First Name of the user","value":"abc","type":"text"}',
    'lname':'{"placeholder":"Second Name","description":"Enter Last Name of the user","value":"ddd","type":"text"}'
  },
  'password':'{"placeholder":"Password","description":"Enter password","value":"","type":"password"}',
  'dim':{
    'dim2':{
      'dim3':'{"placeholder":"Sample","description":"Enter sample text","value":"ssds"}'
    }
  },
  'ary':{
    'ar10':{
      'ary2':{
        'ary3':'{"placeholder":"Sample","description":"Enter sample text","value":"acb"}'
      }
    },
    'ary11':''
  }
}];

 var result='';  

 $scope.mylogic=function(obj,source){ 

   if(typeof source[obj]=='string'){ 
     var val=[];
      if(source[obj]!=""){
    val =JSON.parse(source[obj]);  
      return  obj +' <input type="'+val.type+'" value="'+val.value+'" placeholder="'+val.placeholder+'" type="text" ><br><code>Notes* '+val.description+'</code> <hr>';
     }else{
      return  obj +' <input placeholder="'+obj+'" type="text" > <hr>';
     }
   }else{  // console.log( components[obj] );
     var subObj=source[obj]; var tempObj=[];
      for(item in subObj ){
       // console.log(item,'--',subObj);
       tempObj.push(obj+' > ' +mylogic(item,subObj)  );
      }
     return tempObj;

     /* console.log(tempObj);*/
   }
}



var res=document.getElementById('result');
res.innerHTML=result;
});

Answer №1

I am a bit confused about your exact requirements, but I believe this solution could be beneficial:

<html>

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 
</head>

<body ng-app="myApp" ng-controller="myCtrl">

<form>
First Name: <input type="text" ng-model="data.fname"><br/>
Last Name: <input type="text" ng-model="data.lname"><br/>
Email: <input type="text" ng-model="data.email"><br/>
Age: <input type="text" ng-model="data.age"><br/>
<button>Submit</button>

</form>

<script>
//module declaration
var app = angular.module("myApp",[]);

//controller declaration
app.controller("myCtrl",function($scope){

$scope.data = {fname: "Peter", lname:"Jason",  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47372233223507202a262e2b6924282a">[email protected]</a>", age: 29 };

});

</script>;

</body>

</html>

Answer №2

<form>
        <div ng-repeat="component in components">
            <div >
                <input type="{{ component.name.fname.type }}" placeholder="{{ component.name.fname.placeholder }}" />
                <hr>
            </div>
            <div>
            <input type="{{ component.name.lname.type }}" placeholder="{{ component.name.lname.placeholder }}" />
            <hr>
        </div>
        <div >
            <input type="{{ component.password.type }}" placeholder="{{ component.password.placeholder }}" />
            <hr>
        </div>
        <div >
            <input id="name"  placeholder="{{ component.dim.dim2.dim3.placeholder }}" value="{{ component.dim.dim2.dim3.value }}" />
            <hr>
        </div>
        <div>
            <input  placeholder="{{ component.ary.ar10.ary2.ary3.placeholder }}" value="{{component.ary.ar10.ary2.ary3.value}}"  />
            <hr>
        </div>
        </div>
</form>

https://i.sstatic.net/EXd7A.png

Check out this code example on CodePen

Answer №3

I finally discovered the solution with the help of everyone, thank you! "http://codepen.io/anon/pen/YVzRmZ"

var app = angular.module("inputs", []);
app.filter('unsafe', function($sce) {
    return $sce.trustAsHtml;
});
app.controller("MainCtrl", function($scope, $sce) {

    $scope.components = [{
        'name': {
            'fname': '{"placeholder":"First Name","description":"Enter First Name of the user","value":"abc","type":"text"}',
            'lname': '{"placeholder":"Second Name","description":"Enter Last Name of the user","value":"ddd","type":"text"}',
            'mname': '{"placeholder":"Middele Name","description":"Enter Middele Name of the user","value":"dsdgha","type":"text"}'
        },
        'password': '{"placeholder":"Password","description":"Enter password","value":"","type":"password"}',
        'dim': {
            'dim2': {
                'dim3': '{"placeholder":"Sample","description":"Enter sample text","value":"ssds"}'
            }
        },
        'ary': {
            'ar10': {
                'ary2': {
                    'ary3': '{"placeholder":"Sample","description":"Enter sample text","value":"acb"}'
                }
            },
            'ary11': ''
        },

    }];

    var result = '';


    $scope.mylogic = function(obj, source) {
        if (typeof source[obj] == 'string') {
            var val = [];
            if (source[obj] != "") {
                val = JSON.parse(source[obj]);
                var res = obj + ' <input type="' + val.type + '" value="' + val.value + '" placeholder="' + val.placeholder + '" type="text" ><br><code>Notes* ' + val.description + '</code> <hr>';
                return res;
            } else {
                var res = obj + ' <input placeholder="' + obj + '" type="text" > <hr>';
                return res;
            }

        } else {  console.log( $scope.components);
            var subObj = source[obj];
            var res = '';
            for (item in subObj) {
                // console.log(item,'--',subObj);
                res += obj + ' => ' + $scope.mylogic(item, subObj);
            }
            return res;
        }
    }
})

<html ng-app="inputs">

<head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47262920322b2635692d34077669736976">[email protected]</a>" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
     <script src="script.js"></script>
</head>

<body ng-controller="MainCtrl">

    <div id="result" style="width:600px; text-transform: capitalize;" align="right">Hello
    </div>

    <div ng-repeat="component in components">
        <div ng-repeat="(key, value) in component" ng-bind-html="mylogic(key,component) | unsafe">


        </div>
    </div>

    </div>
    </body>

</html>

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

Inquiry regarding the setTimeout function requiring an answer

I have a question about how setTimeout works. Does it wait for the previous code to finish executing before moving on to execute something else after a set time, or does it simply wait for a specific amount of time and then continue with the rest of the co ...

Ways to verify if Angular has been properly loaded

Imagine if I want to use angularjs from a CDN, but also have a backup in case the CDN request fails - perhaps by pointing to a local js file. For JQuery, there are examples of using javascript like this: if(typeof jQuery == 'undefined') { .. ...

Adjustable width (100%) and set height for SVG

I am attempting to insert an SVG object onto my HTML page with a width of 100% and a fixed height. Upon viewing my fiddle, you will notice that the height of the dark-grey object changes based on the window proportions, which is not the desired outcome. ...

Choose a collection of elements and encase them within a <div> tag

I am currently working on creating a greasemonkey script for a webpage that has a rather challenging structure. My goal is to show and hide different entries, but the content is formatted like this: <a name="first"/> <h3>First</h3> Some ...

Locating the position of multiple repeated words

My question involves a complex laTeX string: let result = "\\frac{x}{2}+\\frac{3}{x}"; The task at hand is to locate the instances of "frac" in the string, store their positions in an array, find the first '}&a ...

Node.js: Attempting to arrange ISO dates based on their time span

I am currently working on creating a line chart using the chart.js library. In order to do this, I have an array that contains ISO dates and my goal is to determine which ISO dates belong to the same hour and day. This information will then be used to gene ...

Resize the tab header in primefaces to fit your needs

Is there a way to change the height of the tabView's header specifically in primefaces? Take for instance the tabs with headers like "God Father I", "God Father II" on this link, I only want to adjust the height of the header and not the entire tab. ...

Using Selenium in Java to interact with popup elements

Attempting to retrieve and interact with pop-up/alert elements using selenium in Java has been a bit challenging for me. Below is the code snippet I have been working on: import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import ...

obtain the .html file as well as the container

Similar Question: jQuery - Get selected element's outer HTML So, I have a div containing some elements: <div id="fred"> It has certain content inside it: <div id="fred"> <tr id="thing1">hello1</tr> <t ...

Discovering the name, id, and class attributes of a RadioButtonList within a content placeholder using JavaScript

Working on a web forms project with a Master Page implementation, I have added the following code in my content place holder. <asp:RadioButtonList ID="ckbLstPartner" runat="server" name="ckbLstPartner" RepeatDirecti ...

Having trouble with Twitter Api version 1.1?

I am facing an issue when trying to display my latest Tweets on my website. Even though everything is working fine on the tweet_json.php, I keep getting the following error when attempting to display them on my site: ReferenceError: listTweets is not defi ...

Javascript recursive method for fetching data entries

Seeking a solution to retrieve interconnected records based on a parent column, where the relation can be one or many on both ends. After attempting a recursive function without success, I found my code became overly complex and ineffective. Is there a st ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

The string obtained from input.getAttribute('value') is lacking one character

While developing e2e-tests for an angular application, I encountered a puzzling issue. When trying to retrieve the value from an using the .getAttribute('value') method, I noticed that a single character was missing. Checking the HTML properties ...

What is the significance of the appearance of the letters A and J in the console for Objects?

After running console.log() in JavaScript code, you may notice some random letters like A and j before or after the Object description in the Google Chrome browser console. What is the significance of these letters? ...

jQuery toggle buttons to show or hide on radio button selection

I have a pair of buttons and a pair of radio buttons Buttons 1) btnErp 2) btngoogle Radio Buttons 1) rdiogoogle 2) rdioErp When I select 'rdiogoogle', 'btngoogle' should be visible while 'btnErp' should be hidden. Conve ...

The second function in Vue.js was unable to initialize the data field within data() due to a missing call for assistance

I have very little experience working with vue js. There are two functions that I am using: loadComponentsOfUser() and loadUserId(). The loadComponentsOfUser() function depends on the userID field being loaded by the loadUserId() function. data() { retu ...

How do you unfocus a React Native TextInput when a button is clicked?

Is there a way to remove the focus from a React Native textInput when clicking on a button? This is how my TextInput is set up: <TextInput onChangeText={onChange} value={searchQuery} placeholder="Start t ...

Updating a particular element within nested arrays: best practices

I have developed a data table containing student records using material UI. Each row represents a different student array with a fee verification button. My goal is to change the fee status when the button is clicked for a specific student, but currently t ...

Can we integrate the Node.js API into Meteor?

Being new to Meteor.js, I've been wondering if it's possible to utilize the node API in my project. I've hit a roadblock and haven't been able to find any information on this topic despite spending a significant amount of time researchi ...