Using Angular's ng-repeat alongside a bootstrap input checkbox, make sure to incorporate a dynamic ng-model and utilize ng-

This particular issue is proving to be a bit challenging for me to articulate, but I'll give it my best shot. I'm currently working on implementing Angular checkboxes with their ng-true-value attribute in conjunction with a dynamic ng-model.

<div ng-app="myApp">
<div ng-controller="MyCtrl">
    <div ng-repeat="asset in asset">
         <h5>{{ asset.title }} categories are...{{ asset.category[0] + " and " + asset.category[1] }}</h5>

        <div class="form-group">
            <label>Business</label>
            <div class="checkbox" ng-repeat="category in categoryFactory.business">
                <input type="checkbox" id="{{category}}" ng-true-value="{{'category'}}" ng-model="asset.category[$index]">
                <label for="{{category}}">{{category}}</label>
            </div>
        </div>
        <div class="form-group">
            <label>Personal</label>
            <div class="checkbox" ng-repeat="category in categoryFactory.personal">
                <input type="checkbox" id="{{category}}" ng-true-value="{{'category'}}" ng-model="asset.category[$index]">
                <label for="{{category}}">{{category}}</label>
            </div>
        </div>
    </div>
</div>

My ultimate goal is that when I load up my asset (as shown below), it will be displayed as depicted in the image here, with the appropriate checkboxes checked. The Business and Personal categories are sourced from a factory, and each checkbox within the form-groups stems from an ng-repeat list defined in the Business/Personal sections of the factory.

$scope.asset = [{
  title: "Sales Agreement",
  category: ["finance-admin", "running-a-business"]
}];

The main challenge lies in correctly implementing the ng-model within the checkboxes. Since each asset can belong to one or more categories, the approach needs to be dynamic. I've attempted to utilize $index to make my ng-model dynamic...

ng-model="asset.category[$index]"

However, this approach does not seem to yield the desired results. It's possible that I am overlooking something simple, so any assistance would be greatly appreciated.

Thank you! By the way, here is the JSFIDDLE link.

Answer №1

According to your $index logic, the arrays categoryFactory.business and asset.category must be the same size. I have provided an updated jsfiddle link for reference.

The key points are:

Firstly, in your case, ng-true-value should be an expression like this

ng-true-value="{{category}}"

Secondly, ensure that the indices of your asset.category array match with the options in your categoryFactory.business array

$scope.asset = [{
    title: "Sales Agreement",
    category: ["", "running-a-business","",  "","finance-admin"]
}];

There may be a better way to handle this without relying on $index, but this solution should work for your situation.

Answer №2

I utilized ng-checked for this task, where a function is assigned as an attribute value. The ng-repeat directive will then evaluate the function in each iteration.

<input type="checkbox" id="{{category}}" ng-checked="isCategory(category)" >

$scope.isCategory = function(category){
   return  $scope.asset[0].category.indexOf(category) >= 0;
}

Within the isCategory() function, we are examining the indices of the category within the asset.category array. If it is found, the function will return true.

Visit this JSFiddle link for more details.

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

A guide to sending props to a CSS class in Vue 3

I need to develop a custom toast component that includes a personalized message and class. While I have successfully passed the message as props, I am encountering difficulties in applying the bootstrap class. Component File: Toast.vue <script ...

Is there a way to properly access and interpret a .log extension file within a React component?

import React from "react"; import "./App.css"; function FileReaderComponent() { const readLogFile = () => { if (window.File && window.FileReader && window.FileList && window.Blob) { const preview = document.getElementByI ...

AngularJS returns two http get requests but only the first one gets resolved

I am a newcomer to angularjs and I am currently working on developing a mobile app using angularjs. I have encountered an issue where the if condition is functioning correctly, but the else condition is not. Specifically, the first http request is working ...

Tips for inserting an item into the parent window: Chrome-specific (compatible with all other browsers)

In my HTML file, I have an iFrame element like this: <iframe src="frame.html" width="2000" height="1000"></iframe> When trying to use jQuery's append function from within the iFrame to add a DIV to the parent window, it works fine in Fir ...

Having trouble with x-editable in Laravel? Changes not being applied?

Trying out x-editable on my Laravel 5.1 website to edit text titles displayed in a table format. After following the documentation, I managed to get the edit form to pop up when clicking on a title. The changes are reflected on the screen but not stored ...

Iterate through an array of objects and add them to a fresh array

I am encountering an issue where I would like to generate a fresh array of objects in order to avoid utilizing a nested array map. However, the error message below is being displayed: TypeError: Cannot read property 'subscriber_data' of undefine ...

Transforming the initial character of a label element into uppercase

When I receive an external HTML page, all the data comes in lowercase. I attempted to capitalize the first letter of each label tag using CSS, but it ended up making the entire text uppercase instead. Here is what I tried: .fontmodal { text-transform ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

Change the image size as you scroll through the window

While my opacity style is triggered when the page is scrolled down, I am facing an issue with my transform scale not working as expected. Any suggestions on how to troubleshoot this or any missing pieces in my code? Codepen: https://codepen.io/anon/pen/wy ...

What is the best way to retrieve data from localStorage while using getServerSideProps?

I'm currently developing a next.js application and have successfully integrated JWT authentication. Each time a user requests data from the database, a middleware function is triggered to validate the req.body.token. If the token is valid, the server ...

extract the text content from an object

I am trying to add an object to the shopping cart. The item contains a key/value pair as shown in the following image: https://i.stack.imgur.com/5inwR.png Instead of adding the title with its innerText using p and style, I would like to find another ...

How about beginning a JavaScript count with a randomly generated number?

As I work on developing this code, I am faced with a challenge: /** * Increment value with random intervals. * @param {string} id - Id of DOM Element. * @param {number} start - Start counter value. Applied immediately- * @param {number} end - End c ...

The Vue.js Vuetify.js error message is saying "A mystery custom element: <v-list-item>, <v-list-item-title> - Have you properly registered the component?"

I followed the instructions from Vuetify Data Iterator Filter section I am able to use various Vuetify components like v-btn, v-card, v-data-table, v-data-iterator, and more. However, I encountered errors only with <v-list-item> and <v-list-item ...

Error message occurring while attempting to inject an AngularJS factory into a controller from an unknown

I'm encountering an issue while trying to inject my factory into the controller in AngularJS. The error message I'm receiving is: Error: $injector:unpr Unknown Provider Despite going through numerous questions and answers, I haven't been ...

issues with jasmine angularjs tests exhibiting erratic outcomes

During the execution of my unit tests, I often encounter a scenario where some random test(s) fail for a specific controller without any apparent reason. The error messages typically look like this: Expected spy exec to have been called with [ Object({}) ...

Using Angular and Laravel to display JSON data extracted from a MySQL database

I am currently retrieving data from MySQL using Laravel query builder, converting it to JSON format as per the suggestion of W3schools. However, when trying to display the fetched data using AngularJS, I end up with a blank page. Laravel route Route::ge ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

Storing the output of asynchronous promises in an array using async/await technique

I am currently working on a script to tally elements in a JSON file. However, I am encountering difficulty in saving the results of promises into an array. Below is the async function responsible for counting the elements: async function countItems(direct ...