How to bind a list of checkboxes in AngularJS - angularjs

I have a list of checkboxes as following :
<div flex="50" ng-repeat="formationType in formationTypeList">
<md-checkbox class="md-warn md-align-top-left"
value="{{formationType.codeFormation}}"
name="formationSelection[]"
ng-checked="formationSelection.indexOf(formationType) > -1"
ng-click="toggleFormationTypeSelection(formationType)">
{{ formationType.nom }}
</md-checkbox>
</div>
This is the format of formationSelection after I send my form :
formationSelection = [
{
codeFormation: 1,
nom: "ENSA"
},
{
codeFormation: 2,
nom: "CPGE"
}
]
In another scenario I want when I open my form to check the checkboxes which are defined in an array as following :
$scope.formationSelection = res.candidatureProjetProfessionnel.formations;
the object res.candidatureProjetProfessionnel.formations contains this :
formationSelection = [
{
codeFormation: 1,
nom: "ENSA"
},
{
codeFormation: 2,
nom: "CPGE"
}
]
And when I inspect $scope.formationSelection it contains the data I got from res.candidatureProjetProfessionnel.formations :
But I don't know why my checkboxes are not checked even though the $scope.formationSelection is not empty.
How can I solve this ?

i'm not sure what the md-checkbox directive is so i'm just going to use a normal checkbox input. Generally speaking, setting a default value for inputs in angular involves 2 things:
Make sure your inputs have ng-model to store the value of the checkbox and for 2 way data binding (so that you can set it from the controller as well)
In your controller set the variable declared in the ng-model to whatever default value you want.
So in you html:
<input type="checkbox" class="md-warn md-align-top-left" ng-
model="formationSelection[$index]" ng-true-value="{{formationType}}"
name="formationSelection[]">
Make sure you use ng-true-value to declare the value of each checkbox when checked. The ng-model is set to formationSelection[$index] which basically means each checkbox is an item inside the formationSelection array, this way the array will be the collection of the values of all checked inputs.
Now $scope.formationSelection = res.candidatureProjetProfessionnel.formations should work
Here's a working plunker:
http://plnkr.co/edit/sGm39DRWH9EOReiiSrIl?p=preview

You have to use ng-model as shown below.It should be an object like $scope.data = {};.This is just an example where hope you can get the point and work on your scenario. Actually you're having individual check boxes as shown below but values are being set through the loop.So you can apply this concept for your use case as well.Hope this will help to you.
Html
<md-checkbox ng-model="data.cb1" aria-label="Checkbox 1">
Checkbox 1: {{ data.cb1 }}
</md-checkbox>
JS
$scope.data = {};
$scope.data.cb1 = true;
Play with it on Codepen

I think that your method isFormation(formationType) on the directive ng-checked it's not return the result.
In your controller create a function
$scope.isFormation(_type){
return $scope.formationSelection.filter(function(f){return f.nom === _type;}).length > 0;
}

Related

Angular: Select dropdown with ng-model-options setter getter set to true

Can somebody show me an example on how to bind ng-options to a getter and setter model, a plnker demo will be great.
Example on what i want to accomplish:
// As you can see the item is a object with two properties example:
// {Text: "hello", Value: 10}
setgetObject: function(value) {
if (angular.isDefined(value)) {
myObject = angular.copy(value); //copy the incoming object
}
return ????
}
<select class="form-control" name="rumFra" ng-model="getterSetter.setgetObject"
ng-options="item as item.Text for item in vm.configuration.Form.Room track by item.Value"
ng-model-options=" {getterSetter: true }">
Each time I make a new selection on my dropdown it will set the myObject with the new value but the dropdown is not effected even if I return the input element.
A working example on how to use Select tag with ng-options and ng-model-options="{setterGetter= "true"}" will be appreciated :-)
Look at Numyx's example:
http://plnkr.co/edit/SqJG8NP7e9NB9okcD4hN?p=preview
Because it is working but not with objects. Can somebody do it with objects?
Just use ng-model . ng-model binds the input,select and textareas.
see the example
<select ng-options="p.name for p in animal"
ng-model="selectedanimal"></select>

AngularJS model not updating inside javascript array

I have a simple issue with AngularJS: the properties outside of the array update normally, but the array elements (that are bound to those properties) don't, here is a plunker to show that: http://plnkr.co/edit/gNtGhiTf228G8rP0O2iB?p=preview
var vm = this;
vm.topLine = {
netWrittenPremiumLastFye: 1000000,
netWrittenPremiumYtd: 123000
}
vm.grossColumnChartData = [
['Previous YE', vm.topLine.netWrittenPremiumLastFye],
['YTD', vm.topLine.netWrittenPremiumYtd]
];
We can use $scope.$watch('something', function(oldValue, newValue) {...}) but that's not a good choice in my situation since i'll have to do that many times, repeatedly.
I want to take advantage of angular 2-way binding as explained above.
Any helps or suggestions are appreciated, thanks!
I think the only way you can do this without using $watch is by updating the array directly in the html binding.
{{ grossColumnChartData = [
['Previous YE', vm.topLine.netWrittenPremiumLastFye],
['YTD', vm.topLine.netWrittenPremiumYtd]
] }}
<br/>
grossColumnChartData = {{grossColumnChartData | json}}
See this:
http://plnkr.co/edit/uthXcvoWSV2XNRFJzkck?p=preview
I have updated my plnkr and i have my answer now: http://plnkr.co/edit/gNtGhiTf228G8rP0O2iB?p=preview
<div ng-repeat="item in vm.grossColumnChartData">
<label>Input {{$index+1}}:</label>
<input ng-model="item.data" type="text"/>
</div>
I was confused between data binding and reference.
I used ng-repeat to update the array elements.

How to expand/collapse all rows in Angular

I have successfully created a function to toggle the individual rows of my ng-table to open and close using:
TestCase.prototype.toggle = function() {
this.showMe = !this.showMe;
}
and
<tr ng-repeat="row in $data">
<td align="left">
<p ng-click="row.toggle();">{{row.description}}</p>
<div ng-show="row.showMe">
See the plunkr for more code, note the expand/collapse buttons are in the "menu".
However, I can't figure out a way to now toggle ALL of the rows on and off. I want to be able to somehow run a for loop over the rows and then call toggle if needed, however my attempts at doing so have failed. See them below:
TestCase.prototype.expandAllAttemptOne = function() {
for (var row in this) {
if (!row.showMe)
row.showMe = !row.showMe;
}
}
function expandAllAttemptOneTwo(data) {
for (var i in data) {
if (!data[i].showMe)
data[i].showMe = !data[i].showMe;
}
}
Any ideas on how to properly toggle all rows on/off?
Using the ng-show directive in combination with the ng-click and ng-init directives, we can do something like this:
<div ng-controller="TableController">
<button ng-click="setVisible(true)">Show All</button>
<button ng-click="setVisible(false)">Hide All</button>
<ul>
<li ng-repeat="person in persons"
ng-click="person.visible = !person.visible"
ng-show="person.visible">
{{person.name}}
</li>
</ul>
</div>
Our controller might then look like this:
myApp.controller('TableController', function ($scope) {
$scope.persons = [
{ name: "John", visible : true},
{ name: "Jill", visible : true},
{ name: "Sue", visible : true},
{ name: "Jackson", visible : true}
];
$scope.setVisible = function (visible) {
angular.forEach($scope.persons, function (person) {
person.visible = visible;
});
}
});
We are doing a couple things here. First, our controller contains an array of person objects. Each one of these objects has a property named visible. We'll use this to toggle items on and off. Second, we define a function in our controller named setVisible. This takes a boolean value as an argument, and will iterate over the entire persons array and set each person object's visible property to that value.
Now, in our html, we are using three angular directives; ng-click, ng-repeat, and ng-show. It seems like you already kinda know how these work, so I'll just explain what I'm doing with them instead. In our html we use ng-click to set up our click event handler for our "Show All" and "Hide All" buttons. Clicking either of these will cause setVisible to be called with a value of either true or false. This will take care of toggling all of our list items either all on, or all off.
Next, in our ng-repeat directive, we provide an expression for angular to evaluate when a list item is clicked. In this case, we tell angular to toggle person.visible to the opposite value that it is currently. This effectively will hide a list item. And finally, we have our ng-show directive, which is simply used in conjunction with our visible property to determine whether or not to render a particular list item.
Here is a plnkr with a working example: http://plnkr.co/edit/MlxyvfDo0jZVTkK0gman?p=preview
This code is a general example of something you might do, you should be able to expand upon it to fit your particular need. Hope this help!

AngularJS ng-repeat default value does not work

I am working with AngularJS and I am so new in that.
My aim is fill a tag SELECT with OPTION element from a datasource.
That is what I do basically:
<script>
function LocalizationController($scope, $http) {
$scope.Regions = [
{ ID: "001", DESC: "DESC_1" },
{ ID: "002", DESC: "DESC_2" },
{ ID: "003", DESC: "DESC_3" },
{ ID: "004", DESC: "DESC_4" },
];
$scope.Region = "003";
$scope.init = function () {
$scope.Region = "003";
}
}
</script>
<div ng-controller="LocalizationController" ng-init="init();">
<input type="button" ng-click="Region='002'" value="test">
<select id="region" name="RegionCode" ng-model="Region">
<option ng-repeat="item in Regions" value="{{item.ID}}">{{item.DESC}}</option>
</select>
</div>
Everything works good, the Select is fill of my items,
but I would like to set default value.
How you can see
- I set my object model which is ng-model="Region"
- I set its default value into init() function by $scope.Region = "003";
when the SELECT is loaded I do not why but dafault value is the first one "001"
I also tried to change value manually by
in that case the SELECT gets the right value selection.
Anyone can explain why it does not work?
I know that is a common problem, I am already looked for that,
any solution suggestion to use NG-OPTION, that directive works good,
it can fill my SELECT with my array of object, it can select default value,
very nice but it does not solve my problem because the value into the
the option element id an integer autoincrement which is not what I want.
so in summary:
NG-REPEAT can render the SELECT how I want but default value does not work
NG-OPTIONS can render the SELECT how I want, default value works but the value into option
item cannot be set how I want.
any suggestions?
thanks in advance
EDIT
I found a "solution"
<div ng-controller="LocalizationController" EXCLUDE-ng-init="init();">
<select id="region" onload="alert();angular.element(this).scope().Region='002'" name="RegionCode" ng-model="Region">
<option ng-repeat="item in Regions" value="{{item.ID}}">{{item.DESC}}</option>
{{init();}}
</select>
</div>
I do not like so much but works pretty good:
- ng-init="init();" does not work good
- If we exclude the initialize of default value into ng-init so EXCLUDE-ng-init="init();" and put the initilize when option are loded it works
Have a look at the code blow, I put {{init();}} after ng-repeat. Everithing works good
{{item.DESC}}
{{init();}}
I do not think is the best solution but Works,
1) I have a droopdown fill of my elements
2) The value of option into my list is CORRECT, "001", "002" and not a stupid autoincremental value which is useless.
I hope that can help someone...
THANKS TO EVERYONE TRIED TO HELP ME
Just use ng-options
<select id="region" name="RegionCode" ng-model="Region" ng-options="option.ID as option.DESC for option in Regions">
And do
$scope.init = function () {
$scope.Region = $scope.Regions[2];
}
When you inspect the select box while using ng-options the values for the options will be like 0,1,2,3.., that is auto increment integer as you said. But don't worry about that. Its the value just for showing up there, but once you post your form you will get the right value as you possess, in your case ID.
use ng-options
and in this case if you play with object (not single values) it should be so
$scope.init = function () {
$scope.Region = $scope.Regions[2];
}

Modifying an array within an object that's displayed in a ng-repeat

I'm trying to update a $scope object's array that is displayed in a ng-repeat on the page using input elements containing the array's contents. The plunker example can be found here: Plunker demo (Basic, stripped down example of my problem)
I have the following settings object defined:
$scope.settings = {
list: ['list item one', 'list item two', 'list item three']
};
and I am representing the data on the page like so:
<ul>
<li ng-repeat="item in settings.list">
<input type="text"
value="{{item}}"
ng-model="singleItem"
ng-change="settings.list[$index] = singleItem" />
delete
</li>
</ul>
My goal is to initially populate the <input> fields with the contents of $scope.settings.list and whenever an item is changed update the array, but I haven't figured out how to in the view. Omitting the ng-model and ng-change on the input properly renders the input vale in the text boxes, but then the array isn't modified when changes are made.
Side Note:
In the Plunker example I have $watch on the settings object. In my actual code, this is used to update a "settings cookie" using the $cookies module. Cookies have been omitted in the example, but for debugging purposes I have left the watch in.
There are two primary problems with your approach. The first is that ngRepeat uses an inherited scope, so primitive values (like strings and numbers) don't play nicely. You should pass arrays of objects to ngRepeat rather than arrays of primitives. Your second problem is the over-complicated way of of binding to an input. All you need is to this:
$scope.settings = {
list: [
{ val: 'list item one'},
{ val: 'list item two'},
{ val: 'list item three'}
]
};
And then in your view:
<ul>
<li ng-repeat="item in settings.list">
<input type="text" ng-model="item.val"></input>
<a ng-click="remove($index)">delete</a>
</li>
</ul>
Here's a revised plunker: http://plnkr.co/edit/ZGFjBnVSwM4hNSgVSOCW?p=preview .

Resources