Implementing Angular checkbox repetition controlled from an external controller

I'm looking to streamline my controller by setting a variable from outside the controller to populate my checkbox list. Can this be done?

Check out my current code snippet here: http://jsfiddle.net/ilmansg/Lx37kr3e/1/

VIEW HTML

<div ng-controller="AdminEventsCtrl">
  <h1>Array 1</h1>
  <ul>
    <li ng-repeat="item in array1">
      <input type="checkbox" ng-model="formData.value1[item.value]" value="{{item.value}}" />
      {{item.text}}
    </li>
  </ul>

  <h1>Array 2</h1>
  <script>
    array2 = [{
    text: 'Option 1',
    value: 'opt1'
  }, {
    text: 'Option 2',
    value: 'opt2'
  }, {
    text: 'Option 3',
    value: 'opt3'
  }, {
    text: 'Option 4',
    value: 'opt4'
  }];
  </script>
  <ul>
    <li ng-repeat="item in array2">
      <input type="checkbox" ng-model="formData.value1[item.value]" value="{{item.value}}" />
      {{item.text}}
    </li>
  </ul>

  <pre>Array1= {{array1}}</pre>
  <pre>Array2= {{array2}}</pre>
</div>

SCRIPT JS

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

function AdminEventsCtrl($scope) {
  $scope.formData = {};

  $scope.array1 = [{
    text: 'Option 1',
    value: 'opt1'
  }, {
    text: 'Option 2',
    value: 'opt2'
  }, {
    text: 'Option 3',
    value: 'opt3'
  }, {
    text: 'Option 4',
    value: 'opt4'
  }];
}

Answer №1

Unfortunately, Angular wouldn't know where to attach the array because of scope confusion. Here's a simplified solution for streamlining your controller:

Create two separate arrays, one for each property text and value.

function ManageEventsCtrl($scope) {
  $scope.formData = {};
  $scope.propertyArray = [];

  var texts = ['Item A', 'Item B', 'Item C'];
  var values = ['a', 'b', 'c'];

  for(i=0;i<texts.length;i++){
      $scope.propertyArray.push({text:texts[i], value:values[i]});
  }

}

Although it may seem like more code, this approach makes your controller much neater and allows for easy addition of new values.

Answer №2

I found a solution by creating a factory to store all of my arrays and then utilizing that factory in my controller.

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

Why won't my timer directive properly update the View as expected?

Experimenting with directives and trying to update the DOM from the directive. The link function in the directive is not able to see the scope controller vars. If you can help me understand what I'm doing wrong, that would be greatly appreciated! I& ...

Incorporating the values of JavaScript objects into a global variable

I'm currently developing a bank account program and facing a challenge in adding my direct debits (DDs) into the global variable. When I create new objects using my constructor function and add them into the bank account, only the last created DD is s ...

Navigating with useRouter().push() from the "next/navigation" package is not functioning as expected when used on a customized signIn page alongside next-auth

Upon logging in successfully on my custom signIn-Page using next-auth, I am facing an issue with redirecting back to the callbackUrl. The setup includes react 18.2.0, next 13.4.8-canary.2, and next-auth 4.22.1. The code for the signIn-Page (\src&bsol ...

What is the best way to destructure an array enclosed within the Promise keyword in JavaScript?

Currently, I am attempting to extract information from a PSQL table using the following code: async function requestData() { var selectQuery = `SELECT "fName", "lName", "phoneNumber", "eMail" FROM public."Use ...

A-Frame VR: Image missing from display on Chrome browser

UPDATE: I discovered that the issue was caused by running the HTML file from my local hard drive instead of a web server. Once I uploaded it to my web server and ran it from there, everything worked perfectly. A-Frame Version: 0.4.0, Chrome: 55.0.2883.87, ...

What's the CSS equivalent of Java's window.pack() method?

I'm relatively new to css and I'm attempting to create a border around a <div>. My goal is for the border to be limited to the size of the elements inside the div and adjust dynamically in proportion to any new objects that may appear or di ...

Utilize the Masonry layout script on dynamically generated elements from AJAX requests

I have been implementing a Masonry script with the following code: var $container = $('.grid'); $container.imagesLoaded(function(){ $container.masonry({ itemSelector : '.grid-item', columnWidth : '.grid-sizer', ...

Strategies for capturing a 404 error in an Express router

Trying to capture the 404 page not found error in an express router. Using a simple example : const express = require('express'); const app = express(); const router = express.Router(); // ROUTER MID BEFORE router.use((req, res, next) => { ...

Explore the possibilities of using a unique custom theme with next.js, less, and ant design

Trying to customize the default theme in antdesign has been a challenge for me. I've switched from sass to less, but there seems to be something that just won't work. I've exhaustively searched online for solutions - from official nextjs ex ...

Extracting public data from social media profiles as displayed in Smartr

Is there any pre-existing API or reference material available for achieving this task? I am interested in accessing public social data without the need for users to manually link their accounts to our site. ...

Transfering data to Handlebars while rendering a template

Is there a method to pass a variable to a handlebars template during its rendering process? Below is the template in question: <script id="listingTopics" type="text/x-handlebars-template"> {{#each this}} <div class="wrapper_individual_listing ...

Sending a CSS class name to a component using Next.js

I am currently in the process of transitioning from a plain ReactJS project to NextJS and I have a question. One aspect that is confusing me is how to effectively utilize CSS within NextJS. The issue I am facing involves a Button component that receives ...

The v-list-group does not automatically expand sub-groups based on the path specified in the group prop

I have a navigation sidebar that includes nested v-list-groups. Based on the documentation, the "group" prop of v-list-group should expand based on the route namespace. To see more information, visit: https://vuetifyjs.com/en/components/lists/ While this ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

Inspecting the Ace Editor within the onbeforeunload event handler to confirm any modifications

I'm attempting to utilize the $(window).on('beforeunload', function(){}); and editor.session.getUndoManager().isClean(); functions within the ace editor to detect whether a user has made modifications to a document without clicking the submi ...

PHP variable missing "+" sign at the end after post operation

I have encountered a unique problem that I cannot seem to find anywhere else. My issue lies in adding grades ending with a plus sign, such as B+, C+ or D+. I am able to add grades like A-, B-, C- and D- without any problem, but when it comes to adding a g ...

When utilizing JavaScript syntax and performing API testing with Postman

Hello, I need some assistance from experts in connecting to Postman using the JavaScript code provided below. When running nodemon, the connection appears to be normal with no errors. Also, the GET request sent to Postman works fine. However, I am encounte ...

`Evaluating the functionalities of AngularJS using Protractor`

Currently, I'm in the process of developing an AngularJS app and have been tasked with incorporating automated testing into our workflow. This is a new concept for me, so it's taking some time to fully grasp. After much consideration, I've ...

How can I extract the text within an element based on the position of the

In my current project, I have incorporated the incredibly useful jQuery TextRange plugin. Within a highlight div positioned above a textarea element, it is crucial for me to identify the specific element that the user is currently editing. To better illust ...

What exactly is the purpose of FormControl and why is it employed? In what ways should FormControl be properly utilized?

I'm a bit confused about how to properly use FormControl in Material-UI when creating forms in React. Can someone simplify for me what exactly FormControl does and why I should consider using it in my project? Currently, I have a Form.js Component wh ...