Dynamic ng-model binding to object properties inside ng-repeater - angularjs

I require a bit of help with AngularJS syntax to make a dynamic checkbox selector bind to object properties.
Problem:
<div ng-repeat="level in vm.Settings.LevelList">
<input type="checkbox" ng-model="vm.Item.Level.{{level.ShortName}}" ng-change="CheckLevel()"> {{level.Name}}
<div>
Where items' level is just a key-value-pair object. It's important to note that not all levels may be applicable to an item but each item will have an object with all possible options as follows:
Item.Level = {
L1: false,
L2: true,
L3: false,
L4: false,
}
My vm.Settings.LevelList changes depending on the page that is loaded. To make things simple let's assume we have the following array to work with:
Settings.LevelList = [
{ Name: 'Level 2', ShortName: 'L2', SortOrder: 2, },
{ Name: 'Level 3', ShortName: 'L3', SortOrder: 3, },
]
My template spells out all possible options where I am using ng-if to hide ckeckboxes that are not relevant. While I am not expecting for levels to change often at the same time I do not want to spend my time tracking every template where level checkboxes apear. So, the following is what I currently have:
<div ng-if="conditon to hide L1"><input type="checkbox" ng-model="vm.Item.Level.L1" ng-change="CheckLevel()"> Level 1</div>
<div ng-if="conditon to hide L2"><input type="checkbox" ng-model="vm.Item.Level.L2" ng-change="CheckLevel()"> Level 2</div>
<div ng=if="conditon to hide L3"><input type="checkbox" ng-model="vm.Item.Level.L3" ng-change="CheckLevel()"> Level 3</div>
<div ng-if="conditon to hide L4"><input type="checkbox" ng-model="vm.Item.Level.L4" ng-change="CheckLevel()"> Level 4</div>
But what I want should be of the following form:
<div><input type="checkbox" ng-model="vm.Item.Level.L2" ng-change="CheckLevel()"> {{level.Name}}</div>
<div><input type="checkbox" ng-model="vm.Item.Level.L3" ng-change="CheckLevel()"> {{level.Name}}</div>
So, the repeater should only need to produce two checkbox options as per Settings.LevelList. Provided the model binds correctly checkbox for Level 2 should be checked (Item.Level.L2 = true).
Just in case someone wonders CheckLevel() just makes sure that at least one level option is selected. Also, I am working with AngularJS v1.5.8.

If your starting object has two items, and you're repeating through it, you would only get two iterations anyway, so it's straightforward. There was a spelling mistake in your repeat, where you had 'ShortName' but in the date you had 'ShartName' so I've amended the input to display that.
<div ng-repeat="level in vm.Settings.LevelList">
<div>
<input type="checkbox" ng-model="vm.Item.Level[level.ShartName]"
ng-change="CheckLevel()" /> {{level.Name}}
</div>
<div>

Related

Based on dropdown value show div inside ng-repeat

The below thing is taking too much time than expected. Been through top stack solutions and somehow got the below thing--
WHAT IS THE SCENERIO
I have an ng-repeat div with dropdown.
The drop down contains values and based on selection of those values a div will be shown. What I managed is div is shown. But when I choose another item the previous item div gets hidden.
Below are the screen shot and my code
As it can be seen that when I select the first item it shows the textbox div. But when I select the next item the first gets hidden. There are essentially two values -- ALL, Fixed. When All selected nothing will be shown and when Fixed is selected the div for that particular item will be shown.
HTML code
<div class="tst text-success" ng-repeat="(parentIndex, catList) in categoryArray">
<div class="col-md-3">
{{catList.categoryName}}
</div>
<div class="col-md-4">
<select class="form-control m-b" ng-model="catObj.cats" ng-change="changeOption(catObj,parentIndex)">
<option value="All">All</option>
<option value="fixed">Fixed No. Of Records</option>
<option value="perfixed">% od Fixed</option>
</select>
</div>
<div class="col-md-3 noPad" ng-if="isShowing==parentIndex">
<input type="text" class="form-control form-control-small" placeholder="Set Number" />
</div>
</div>
CONTROLLER
$scope.changeOption = function(obVal,index) {
console.log(obVal);
console.log(index);
if(obVal.cats == "All") {
//$scope.tbx = 0;
}
else {
$scope.isShowing = index;
}
}
Help would be appreciated
Thanks
You're using a single boolean $scope variable, isShowing, to control the visibility of several divs. That can't possibly work.
You should
have an array of objects, each having a selectedOption field.
use ng-model in your select box to set the selectedOption of the object you're editing.
use the value of the object's selectedOption to know if the additional input should be visible for that object.
Example:
<div ng-repeat="obj in objects">
{{ obj.name }}
<select name="op" ng-model="obj.selectedOption" ng-options="option.value as option.value for option in options"></select>
<input ng-if="obj.selectedOption !== 'All'" />
</div>
app.controller('MainCtrl', function($scope) {
$scope.options = [
{value: 'All'},
{value: 'Fixed'}
];
$scope.objects = [
{name: 'Twitter', selectedOption: 'All'},
{name: 'News', selectedOption: 'Fixed'}
]
});

How to access from parent form to a certain child form generated in ng-repeat without the need to add things like frmChild {{$index}}?

How to access from frmParent to a certain frmChild? (without the need to add things like: frmChild {{$index}}).
<div ng-form="frmParent">
How to know frmChild (i.e at index 3) $pristine value from HERE
<div ng-form="frmChild" ng-repeat="item in mct.listOfElements">
{{item.Name}}:
<input type="text" ng-model="item.Value" /> Pristine: {{frmChild.$pristine}}
</div>
</div>
Here is a working example to play with what i'm talking about.
You can use unique names for your child forms, ex. item.Name if it's supposed to be unique:
<div ng-repeat="item in mct.listOfElements" ng-form="{{item.Name}}">
{{item.Name}}:
<input type="text" ng-model="item.Value" /> Pristine: {{frmParent[item.Name].$pristine}}
</div>
And then refer to any required child form by it's name:
D now is pristine: {{frmParent.D.$pristine}}
Please see the Plunker.

Dynamic Attributes with AngularJS

In some cases I need to apply different attributes to a node based on properties in my model.
For example, in one case I need to add a 'required' tag and in another case not. I've been using ng-if with different branches to accomplish this but the cases are getting out of hand quickly.
<div ng-if="model.required">
<input class="form-control"
type="text"
required
ng-model="model" />
</div>
<div ng-if="!model.required">
// as different options arise,
// i have more forks for each attribute combo
<input class="form-control"
type="text"
ng-model="model" />
</div>
Is there a better way to dynamic apply attributes to nodes?
I have quickly created a directive that allows you specify attributes dynamically.
http://jsfiddle.net/HB7LU/1806/
I'm not sure if it will have the desired effect you are after in this simple form, but it might be a good starting point. You essentially use:
<div dyn-attrs="someModelArray"></div>
And set your model accordingly:
$scope.someModelArray = [
{ attr: 'myattribute', value: '' },
{ attr: 'anotherattribute', value: 'val' }
];
In this case it would be best to make use of ngRequired:
<input class="form-control" type="text" ng-required="model.required" />

How to bind ng-model to ng-checked boxes

I am having a problem binding Angular ng-check to ng-model, that is ng-model does do not recognize the selected state of my check boxes.
Here is a description(Its a much larger code base but I have tailored to minimize code).
On page load in JavaScript I initialize my products and set the default values:
$scope.products = {}
$scope.SetProductsData = function() {
var allProducts;
allProducts = [
{
id: 1,
name: "Book",
selected: true
}, {
id: 2,
name: "Toy",
selected: true
}, {
id: 3,
name: "Phone",
selected: true
}]
I have a master control in my view that list a check box for each 3 products(Book,Toy and phone):These are checked by default
<div style="float:left" ng-init="allProducts.products = {}" >
<div ng-repeat="p in Data.products">
<div style="font-size: smaller">
<label><input id="divPlatorm" ng-model="products[p.name]" ng-init="products[p.name] = true" type="checkbox"/>
{{p.name}}</label>
</div>
</div>
</div>
Then a table that have the same products repeated in rows:
<div ng-repeat="line in lineProducts" ng-init="line.products = {}">
<div id="sc-p-enc" ng-repeat="p in Data.products">
<div id="sc-p-plat" style="font-size: smaller">
<label id="pl-label"><input ng-checked="products[p.name]" ng-model="line.products[p.name]" ng-init="line.products[p.name] = true" type="checkbox"/>
{{p.name}}</label>
</div>
</div>
</div>
When I check/unchecked the master products the corresponding check boxes changes in the rows. So if I have 100 rows with (Book,Toy and phone) the unchecked Toy I can see where all toys are unchecked in the rows.
When I send the data to my controller I can still see all Toys = true even though they were unchecked.
If I physically go to the row then unchecked each toy and send the data to my controller Toys = False.
How can I get the check boxes selected state to change when controlled from the master check-boxes?
I have followed the post found here but I dont think this applies to my scenario:
AngularJS: ng-model not binding to ng-checked for checkboxes
It seems the ng-checked in the table is binding to products[p.name], which the ng-model in your master control in the view also binding to. But the ng-model in your table is binding to another property, line.products[p.name].
I think you probably don't need ng-checked in the table since each item has its own ng-model. So you might change your table view to
<label id="pl-label"><input ng-model="line.products[p.name]" type="checkbox"/>{{p.name}}</label>
and in the controller, change the corresponding value of line.products[p.name] every time the value of products[p.name] is changed.
I just solved this problem myself by using "ng-init" and "ng-checked" ---
ng-checked - 'checked' the checkbox as form was loaded
ng-init- bound my checkbox html value attribute to the model
There is a comment above stating that its not good to use ng-init in this manner, but not other solution was provided.
Here is an example using ng-select instead of ng-checked:
<select ng-model="formData.country">
<option value="US" ng-init="formData.country='US'" ng-selected="true">United States</option>
</select>
This binds "US" to model formData.country and selects the value on page load.
If I understand the functionality you are trying to cover the following fiddle might help you. Here is the code:
<div style="float:left" ng-app ng-init="products = [
{
id: 1,
name: 'Book',
line: 'Books',
selected: true
}, {
id: 2,
name: 'Another Book',
line: 'Books',
selected: true
}, {
id: 3,
name: 'Toy',
line: 'Toys',
selected: false
}, {
id: 4,
name: 'Another Toy',
line: 'Toys',
selected: false
}, {
id: 5,
name: 'Phone',
selected: true
}];lineProducts = ['Toys', 'Books']" >
<div style="float:left">
<div ng-repeat="p in products">
<div style="font-size: smaller">
<label>
<input ng-model="p.selected" type="checkbox"/>
{{p.name}}
</label>
</div>
</div>
</div>
<div ng-repeat="line in lineProducts">
{{line}}
<div ng-repeat="p in products | filter:line">
<div style="font-size: smaller">
<label>
<input ng-model="p.selected" type="checkbox"/>
{{p.name}}
</label>
</div>
</div>
</div>
</div>
Also why do you have ids in your html? With angular there is no need in ids, and considering that they are inside ng-repeats they will be ambiguous and therefore useless anyway.
I also agree with Nikos about usage of the ng-init. I used it in my jsfiddle because I am lazy, I would not use it in the production code
You should use ng-model there that would provide you two way binding. Checking and unchecking the value would update the value of product.selected
<input type="checkbox" ng-model="p.selected"/>

Angular - Filtering with checkboxes

I am new to Angular and i just cant wrap my head around that problem.
I have several checkboxes which will have a unique value each, like so:
<label ng-repeat="c in classes">
<input type="checkbox" ng-model="query" ng-true-value='{{c.name}}'>
<span>{{c.name}}</span>
</label>
Next i have this set of divs that should be filtered on a specific value like card.name , like so:
<div ng-repeat="card in cards | filter:query">
<h2>{{card.name}}</h2>
<p><em>{{card.text}}</em></p>
</div>
When checkbox with value 'Peter' is checked, all cards with card.name=Peter are shown. When checkbox 'Peter' and 'John' are shown all cards with card.name=Peter and =John are shown. How can i realize this?
I guess its more of a general concept/markup question...
You don't need to have two different variables, in fact that is the problem. Angular doesn't know how to tie them together.
The filter can look deep into the object for a specific key set to a specific value. In my example the filter looks for this particular selected attribute, only showing ones that are set to true Keeping everything in the same object keeps everything tied together.
<label ng-repeat="c in classes">
<input type="checkbox" ng-model="c.selected" />
<span>{{c.name}}</span>
</label>
<div ng-repeat="card in classes | filter:{selected:true}">
<h2>{{card.name}}</h2>
<p><em>{{card.text}}</em></p>
</div>
Here is the data:
$scope.classes = [{
name: "John",
text: "Something about John"
},{
name: "Peter",
text: "Something about Peter"
}];
Note: that a selected attribute is added to each object when it is selected. This is the key we are filtering on.
Working example: http://jsfiddle.net/TheSharpieOne/y2UW7/
UPDATE:
After re-reading the question, it appeared to me that there would be multiple cards for the same name. A different approach would be needed.
In this case, multiple variables are needed, a list of checkboxes and a list of "cards". We also need a var to track which boxes are selected.
In this case we use a function to filter the list as 1 checkbox could change many "cards"
Example: http://jsfiddle.net/TheSharpieOne/y2UW7/1/

Resources