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

Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange. export class Test {range: IntervalRange;} Then, in the parent class, I initialize the value: export class TestInitializer { Create(){ return <Test>{ range: IntervalRange.i ...

Avoid having Masonry load all divs simultaneously

I have experience using jQuery Masonry on Tumblr, but now I want to incorporate it into my portfolio website for displaying my photography. However, I'm struggling to find a solution that allows sets of images to load in as the user scrolls to the bot ...

How can I store the content of a meta tag in a JavaScript variable?

Similar Question: How can I extract data from a meta tag using JavaScript? I have a meta tag that can be customized with content on a specific page, and I'm looking to retrieve this content as a variable in JavaScript. ...

Comparing the benefits of using npm cache clean versus npm cache verify

Can you explain the distinction between the two commands below? npm cache clean npm cache verify Additionally, what is the purpose of the force option? I am particularly interested in how these commands work in a Windows development environment. ...

Steps for setting the value of a textbox within a bootstrap popover

When a user clicks on an Anchor element, I am displaying a Bootstrap popover using the following JQuery code. Jquery $("[data-toggle=popover]").popover({ trigger: 'click', placement: "top", html: true, ...

Merge information from various sources using ajax

Currently, I have a single ajax request that retrieves data from an API and uses it to generate a table. Now, I'm looking to modify the code so that it can retrieve data from two different URLs and merge them into the same table (retTable). Below is ...

Employing DOM manipulation within Vue unit tests as a last resort

What steps should I take to update my unit test in order to accurately validate the following scenario? Method: close(event) { const element = !!event?.target?.closest('#target') if (!element) { this.isVisible = false } }, Jest test: ...

Creating a "Container" component in Vue.js step by step

As a newcomer to Vue, I am facing a challenge in implementing a wrapper component similar to React's 'Wrapper' component. Specifically, I want to create a reusable datagrid component using a 3rd-party some-table component and a pagination co ...

Generating a hierarchical structure of JSON data through iterative looping

Currently, I am in the process of creating a directive within Angular to assist with field validation. The functionality is working smoothly until it comes time to store the validation result. My objective is to store this information in an object structu ...

Utilizing AngularJS to create bound checkboxes

I am struggling with two checkboxes, one with Data Binding and the other without Data Binding. The code snippet below illustrates this: <html ng-app="notesApp"> <head><title>Notes App</title></head> <body ng-contro ...

Investigating nearby table cells

I am in the process of creating a game called Dots and Boxes. The grid is filled with numerous dots: <table> <tr> <td class="vLine" onclick="addLine(this)"></td> <td class="box" ...

The button's onclick function is not triggering with just one click

I am having trouble with a JavaScript function not being called on the first click. I have to click the button multiple times for it to execute. Here are the methods I have attempted so far: <a href="javascript:delete_todo(4);void(0)"><img border ...

Are routes in Next.js easy for search engines to crawl?

Currently, I am developing a movie application using NextJS to enhance my skills. The homepage features each movie's title and a brief description. When a user clicks on a movie, they are taken to a dedicated page that showcases more details about the ...

Is there a way for me to discover the identity of the victor?

There are 4 divs that move at different, random speeds each time. I am trying to determine which one is the fastest or reaches the goal first. Additionally, there is a betting box where you can choose a horse to bet on. I need to compare the winner with my ...

Determine the width of the window and adjust the positioning of jQuery UI tooltips accordingly

Struggling to adjust the jQuery UI tooltip position based on screen width, but can't seem to figure it out. Can someone assist me in detecting the browser's width and changing the tooltip position accordingly? [fiddle] $(function () { $(doc ...

Is it advisable to compress my API response in PHP?

At this stage, I find myself needing to generate extensive reports in order to gain a better understanding of the data at hand. To do so, I must retrieve one of my tables which contains around 50 parameters and 40,000 rows. While fetching the data via API ...

What is the method to retrieve JSON data with data['file.file']?

When trying to query my data using var x = data.file.file;, I encountered an issue where data['file.file'] fails. Is there a way to access this data without having to split the string and walk recursively through it? ...

Learn the step-by-step guide on integrating Angular 2 into Codeigniter 3

Currently, I am using Codeigniter 3x and have been using and learning it for a month. Now, I want to start learning a JavaScript framework like Angular, but I'm not sure how to install or use Angular in Codeigniter. Can anyone guide me on this? Is it ...

The failover process for PayPal involves seamless transitions to backup systems in the

I am currently assisting a client with a unique architecture setup: Back End Running on Java Server Front End Powered by Proxy (Node JS + Express application) For security reasons, all requests made to the server must pass through the Proxy. We ar ...

What could be causing this code to malfunction on jsfiddle?

Why doesn't this code from W3schools work on jsfiddle? I tried to implement it here: https://jsfiddle.net/u6qdfw5f/ <!DOCTYPE html> <html> <title>W3.CSS</title> <meta name="viewport" content="width=device-width, initial ...