Can a model be generated using Angular view values?

I am facing a challenge with a form that has complex functionality such as drag-and-drop, deleting groups of elements, and adding groups of elements. I want to leverage Angular for this task. The form is already rendered with original values set.

<form>
    <div>
        <input ng-model="rule[0].rule" value="bar">
        <select ng-model="rule[0].value">
            <option>A</option>
            <option selected>B</option>
        </select>
    </div>
    <div>
        <input ng-model="rule[1].rule" value="foo">
        <select ng-model="rule[1].value">
            <option selected>1</option>
            <option>2</option>
        </select>
    </div>
    ...
</form>

My issue lies in Angular nullifying these values and failing to create a rule array in the $scope. My goal is to generate an array of objects called rule based on the values in my template.

While I understand that my approach may not align perfectly with the MVC pattern due to data being provided by the template, I prefer to avoid extensive data parsing methods.

Thank you.

Answer №1

Simply put, it cannot be done.

Prior to utilizing it in your view, you must establish $scope.rule as an array within your controller.

$scope.rule = [];

You will encounter limitations in adding content to your $scope within the view...

Answer №2

It appears that your form contains two very similar pieces of code, and it is likely that you will add more in the future. To streamline your code, consider hosting all representations in the controller and building from there. Below is an example to illustrate this approach:

View

<div ng-repeat="item in options">
    <input ng-model="item.rule">
    <select ng-model="item.value">
      <option ng-repeat="option in item.options" ng-value="option">{{option}}</option>
    </select>
    <span>{{item.value}}</span>
  </div>

Controller

  $scope.options = [{
    value: 'B',
    rule: 'foo',
    options: ['A', 'B']
  }, {
    value: 2,
    rule: 'bar',
    options: [1, 2]
  }];

https://jsfiddle.net/rzadc03v/

I hope this example proves useful for you!

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

I am puzzled by the issue with my logic - the button only changes once and then the onclick function ceases to work

I am having an issue with a button that should switch between displaying temperatures in Fahrenheit and Celsius when clicked. It works for the first two clicks, but on the third click, it stops working even though I've set the class back to .temp. $( ...

Issue: 'The server cannot be started because the path is not defined' error message appears

Hey everyone, I'm currently working on implementing a forgot/reset password feature for my React Native app using this tutorial. However, when attempting to start the server, I encountered an error related to the 'path'. ReferenceError: pat ...

What is the best way to create this server backend route?

I'm currently working on a fullstack project that requires a specific sequence of events to take place: When a user submits an event: A request is sent to the backend server The server then initiates a function for processing This function should ru ...

VueJS Router error: The variable $route is undefined

Check out my component: const Vue = require("vue/dist/vue.js"); const qs = require("querystring"); module.exports = Vue.component("Page",function(resolve){ console.log(pageRoute); let id = pageRoute.params.id; fetch("/getPage.json",{ ...

Angular UI-Router: Difficulty in Child State Accessing Parent Controller

I am currently using ui.router's nested views feature in my Angular application. Here is the relevant part of my .config: $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: '/', templateUrl: ...

JavaScript's ASYNC forEach function not following the expected sequence

I'm really struggling to understand the workings of async and await in this scenario. I want the forEach function to run before the console.log and res.json, but no matter what I do with async and await, it always ends up being the last thing executed ...

Learn how to showcase specific row information in a vuetify data table on Vue.js by implementing icon clicks

I am currently working on a Vuetify data table that showcases order information, with an option for users to cancel their orders by clicking on the cancel icon. Upon clicking the cancel icon, a confirmation overlay pops up displaying the specific order id. ...

What is the best way to stack several elements on top of each other?

<div class="parent"> <div class="child" id="child-A"> <div class="child" id="child-B"> <div class="child" id="child-C"> </div> The main concept here ...

Utilizing JavaScript in Selenium WebDriver, what's the procedure for extracting element information from a script tag?

I'm facing an issue with this particular page There is a canvas element on this page that displays changing numbers whenever the page is refreshed or reloaded. Looking at the source code, I can only find the following: <div class="row"> ...

the object '[object Object]' of a distinct supporting nature

I encountered an error stating "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." This is my TypeScript file: this.list = data.json(); ...

Is there a way to output several lines from a JSON file in print form?

I'm working with HTML code that displays multiple lines from a JSON file, but it only shows one line at a time. How can I modify the code to display all users' information? <!DOCTYPE html> <html> <head> <script> function ...

Filter object in Angular to remove empty values

Below are the specific data sets: $scope.icons = [{ "id": 1, "bonuses": [ { "id": 1, "name": "Rob", "amount": 10, "foreman": 1, "percA": 1, "percB": 0 }, { "id": 2, "name": "Mark", "amount": 20, "foreman": 1, "percA": 1, "percB": 0 }, ] }, { ...

The AJAX request is not triggered before the postback when using a LinkButton in ASP

I am facing an issue with running an insert statement using a button in my application. Although it is functional, I have noticed that whenever I click the button, the Page_Load function runs before the ajax statement executes. How can I ensure that the a ...

Retrieve URL query parameters using AngularUI

I am currently working with the AngularUI library and I am trying to retrieve the query parameters from a URL (for example: #\books\:categoryID?publisher=xyz or #\books\value?publisher=xyz). When using $stateParams, the data is extract ...

Exploring the functionality of date picking in Angular.js

Can anyone help me figure out how to search or filter using a jQuery date picker in Angular? I've noticed that Angular doesn't recognize the data inserted by jQuery. I've experimented with Bootstrap date picker, jQuery date picker and HTML5 ...

Learn the process of playing a video in an HTML5 video player after it has finished downloading

// HTML video tag <video id="myVideo" width="320" height="176" preload="auto" controls> <source src="/server/o//content/test2.mp4" onerror="alert('video not found')" type="video/mp4"> Your browser does not support HTML5 vid ...

How to effectively utilize `MutationObserver` for monitoring the properties of an `HTMLElement` instead of focusing on its attributes

By using the MutationObserver.observe() method, I am able to monitor changes in a specific attribute. For instance, if I have a Div element and the attribute value is modified, then the designated callback function will be executed. However, if the propert ...

What is the benefit of storing an IIFE in a variable?

When it comes to using IIFE in JavaScript and AngularJS, I have come across two common structures: Structure 1: //IIFE Immediately Invoked Function Expression (function () { }()); However, there is another structure where the IIFE is assigned to a var ...

Invoking a function from a separate JavaScript file and finding out that an object is considered null

The source code for a word game is stored in Main.js file. Currently, I am attempting to introduce another file called Bookmarks.js (included on the web page prior to the Main.js file). This new file will contain an object var bookmarks = {}; that stays s ...

Vue.js methods bound as properties on a parent object

There are times when I come across scenarios where it would be convenient to bind methods as an object property rather than a direct Vue method. For instance, instead of: <MyInput :formatter="currencyFormat" :parser="currencyParser& ...