The dynamic view of AngularJs' model

I am attempting to create a feature in this app where users can click "Add" to add any category they want in a form. I will save all of them and then output them, but I'm having trouble with the output part.

For a dynamic view example, you can check out: http://plnkr.co/edit/j5RGMi3RTPZ85XGvaa2D?p=preview

The javascript file looks like this:

var app = angular.module('plunker', []);

app.controller('ctrl',['$scope', function($scope){
    $scope.templates = [];
    $scope.addTemplate = function(){
        $scope.templates.push('category');
    };
}]);

The view includes:

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

 <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54353a33213835267a3e2714657a647a2c">[email protected]</a>" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" data-semver="1.0.8"></script>
    <script src="app.js"></script>

<p>Click button to add Category</p>
<button ng-click="addTemplate()">Add Category</button>
<div ng-repeat="template in templates">
<ng-include src="template"></ng-include></div>

<script type="text/ng-template" id="category">
<form class="form-horizontal">
  <div class="form-group">
      <label class="col-sm-2 control-label" for="categoryTitle">Title</label>
      <div class="col-sm-10">
          <input id="categoryTitle" name="categoryTitle" ng-model="category.title" type="text" class="form-control" placeholder="Input your category title" required>
      </div>
  </div>
  <br>
  <!-- Begin textarea -->
  <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
          <textarea id="nonresizable" class="form-control" ng-model="category.content" placeholder="Input your category content here" rows="5" required></textarea>
          <hr>
      </div>
  </div>
  <!-- End textarea -->
</form>

 <p>The inputed Category</p>

 <label>Title</label>
 <div>{{category.title}}</div>
 <div class="col-sm-offset-2 col-sm-10">
    <textarea>{{category.content}}</textarea> 
    <hr>
</div>

Your feedback and thoughts are highly appreciated!

Answer №1

Are you looking to update the content in $scope.templates after adding a note or page?

If you wish to modify the content of each note within the template, you can achieve this by following these steps:

var app = angular.module('plunker', []);

app.controller('ctrl',['$scope', function($scope){
$scope.templates = [];
$scope.addTemplate = function(){
    $scope.templates.push({
        content1 : "newContent1",
        content2 : "newContent2",
        content3 : "newContent3"
});
};

Answer №2

Here is an example of how you can create something similar:

Just a proposal

Using Templates.js


var tempsObj = {} | tempsObj;
tempsObj.templates = function(){
 var template = [];
 template ["templates1"] = "folder1/";
 template ["templates2"] = "folder1/";
 return template;
}


tempsObj.selectedTemp = "templates1";

Implementing Module.js


var app = angular.module("plunker",['ngRoute']);

home.config(function($routeProvider,$locationProvider){

$routeProvider

    .when('/',{

        templateUrl : tempsObj.templates[tempsObj.selectedTemp]+'plunker.html',
        controller : 'plunkerController'
    })
    .when('/404',{
        templateUrl : tempsObj.templates[tempsObj.selectedTemp]+'404.html',
        controller : '404Controller'
    })
    .otherwise({
        redirectTo : '/404'
    });
});

Answer №3

After conducting further research, I successfully managed to make it work! Hooray!

If you'd like to see a live demonstration on Plunker, feel free to click on this link: http://plnkr.co/edit/DFG45HJ67TYUIopLKM?p=preview.

$scope.addField = function() {
  $scope.data.fields.push({
  content: "new entry " + counter++
});

};

The goal is to dynamically add a name for each category and append the new category to the scope every time. I hope this clarifies things.

A big thank you to everyone for their input and assistance!

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

Removing elements from an array based on a specified condition

I am having trouble deleting JSON elements that meet a certain condition. I tried using the following code: var index = -1; for (var i = 0; i < data.dashLayout.dashlets.length; i++) { if (data.dashLayout.dashlets[i].rowNo == selectedrowno) { if ( ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Error: Code cannot be executed because the variable "sel" has not been defined in the HTML element

Every time I try to click on the div, I encounter an error message stating 'Uncaught ReferenceError: sel is not defined at HTMLDivElement.onclick' I am currently developing with Angular 8 and this error keeps popping up. I have read through simil ...

Create an additional column in HTML using Bootstrap styling

I am currently working on a CRUD form (using PHPMyAdmin for the database), developed in HTML, JavaScript, and PHP. The queries are executed using jQuery. I am facing an issue with my code - whenever I add a new column to my table, the formatting gets messe ...

Divide a string within a JSON object and output it as an array

I've encountered a challenge while working with data received from an API. My goal is to loop through this information and generate HTML elements based on it. The issue lies in the 'subjects' data, which arrives as a string but needs to be m ...

Converting a JSON array into a table using AngularJS

Here is the structure of my JSON data: [{"Name":["A","B","C","D","E","F"], "Age":["20","30","40","50","55","60"], "Gender":["M","M","F","M","Unknown","Unknown"]}] I am looking to create an AngularJS table that resembles the following format: Name Age ...

Send certain attributes from the main component to the subcomponent

When dealing with components, I often find myself needing to manipulate specific children based on their type. For example, in the code snippet below, I want to set additional props on a child component if it matches a certain type: import React from &apo ...

Having trouble retrieving JSON data using http.get method, as the status returned is -1

I'm a beginner in AngularJS. I'm attempting to retrieve JSON data in my code using $http.get, but it's throwing an error and the status is showing as -1. What could be causing this issue? RecordApp.factory('recordaccess', [' ...

Utilize a custom JQuery script on designated grid displays

I am facing a challenge in implementing a JQuery script on specific Gridviews within my page. The issue lies in the fact that the script is currently being applied to all Gridviews on the page, and I need a way to specify which grids it should apply to. T ...

(Vue with Typescript) Error: Component cannot be mounted as template or render function is not defined

Having trouble mounting component due to template or render function not defined. Hello everyone, I'm currently attempting to incorporate Typescript into my Laravel / Vue project. However, I've been encountering issues such as the following erro ...

Angular 2 App Encountering Async Pipe Issue with Observable

I have successfully implemented pagination in my Angular 2 application, but I am encountering an issue related to the async pipe: Invalid argument '' for pipe 'AsyncPipe' Upon researching this error, it seems to be linked to the asy ...

Is there a way to filter and tally the JSON objects that have latitude and longitude within a 10km radius from the

I'm currently working on filtering and counting objects from an API endpoint that fall within a 10km radius of the specified origin. My main challenge lies in correctly filtering the API results and tallying the number of matching items. While I succ ...

Having issues with the link page in react-router-dom?

Currently, I am utilizing the react-router-dom library to manage routers. However, I have encountered an issue where linking to another page does not change the page, but instead adds the new page right after the previous one as shown in the image below. W ...

What do cross-domain requests, cross-domain attacks, and cross-domain protocols entail?

Can anyone provide clarification on the concepts of cross domain requests, cross domain attacks, and cross domain protocols as they relate to the AJAX terminology? ...

What is the best method for retrieving the complete error message from my client-side Node and Express server?

When I send a request to my express route and it returns a 400 status along with an error message, I am facing an issue on the client-side. The alert message only displays "Object object" instead of the actual error message that I see on the server side. U ...

What is the best way to determine if a string includes values from an array?

After taking a brief hiatus from coding, I'm diving back in and working on a userscript for a Facebook game. The script will gather data from all game-related posts and use that information to kickstart the accepting process. Currently, I'm stru ...

What are the steps to manipulate third party API data with the Node.js 'Request' module, prior to transmitting it to the frontend?

Being a newcomer to NodeJs, I took to Google for assistance but came up empty. My challenge lies in editing the json data retrieved from an API link and sending it to frontend AngularJS as is. app.get('/getCustomers', bodyParser.urlencoded({exte ...

Having trouble getting a Mocha test to display two decimal places in Javascript? Both Big and Decimal libraries are causing issues

After encountering an error with the Big library, I decided to switch to Decimal. First, I ran npm install Decimal Then, I added the following code: const Decimal = require('decimal'); Even after following the examples, my comparison returned { ...

Scrolling Down on a Jquery Login Page

I am currently utilizing JQuery version 1.4.2. My objective is to allow the user to scroll down to the login form by clicking on the 'login' option in the top menu, similar to Twitter's design. The implementation works impeccably with insert ...

How can you pre-load SVG images in an Ionic view?

After developing a mobile app using Ionic, I encountered a slow loading time for one specific view that includes a large SVG image of 202KB. The delay in loading the view/page can be frustrating as it takes around 3-4 seconds to fully load and display. Is ...