How to change an object's property in AngularJS - angularjs

I have a function that sets a property in an object to false if it's true and true if it's false. Yet every time the function runs the object doesn't get affected.
$scope.menuButtons = [{header: "beaded", isActive: false},
{header: "laced", isActive: false}
]
$scope.activeButton = function(isActive) {
isActive == true ? isActive = false : isActive = true;
};
Here's the HTML
<div ng-repeat="b in menuButtons">
<div ng-click="activeButton(b.isActive)" class="shop-navbar-button">{{b.header}}</div>
</div>
I'm using the isActive value to see if the button is active so I can use a different class. For some reason the isActive value in the $scope doesn't get affected.

Pass in b instead of b.isActive. The boolean is just being passed by value, so re-assigning the value will have no effect on b.isActive.

I think you can change from this:
<div ng-click="activeButton(b.isActive)" class="shop-navbar-button">{{b.header}}</div>
to this:
<div ng-click="b.isActive=!b.isActive" class="shop-navbar-button">{{b.header}}</div>
You will NO need the auxiliar function. It is cleaner and more angular way.

Related

Boolean value is not set in view, but is in controller

In my TaskHandler module I have a TaskOverviewController.ts:
$onInit() {
this.observeTaskUpdates();
}
private observeTaskUpdates(): void {
showTaskDetailView$
.subscribe(value => {
this.showTaskDetailView = value
console.log('value', value);
console.log('this.showTaskDetailView', this.showTaskDetailView)
});
}
This TaskOverviewController is linked to the TaskOverview.html:
<div id="grid-container" class="dashboard-container" ng-controller="TaskOverviewController as vm">
ShowTaskDetailView: {{vm.showTaskDetailView}}
<div id="main" ng-if="vm.showTaskDetailView">
show if true
</div>
</div>
On a different module CustomerService I have a ActivityTimelineItemComponent.ts:
public showDetailTaskView() {
showTaskDetailView$.onNext(true)
}
When I trigger the showDetailTaskView()function on the ActivityTimelineItem.html I get routed to another page,
<div >
<i
ng-click="vm.showDetailTaskView()"
ui-sref="dashboard.tasks.overview.details.information({ id: activity.task.id})"
>reply</i
>
</div>
And this is on the console:
TaskOverviewController.ts:31 value true
TaskOverviewController.ts:32 this.showTaskDetailView true
TaskOverviewController.ts:31 value true
TaskOverviewController.ts:32 this.showTaskDetailView true
But the #main element is not visible in the DOM. And the ShowTaskDetailView: {{vm.ShowTaskDetailView}} is also not showing the controllers set value.
I've tried wrapping the .subscribe in the TaskOverviewController in a timeout, but that didn't work either. So why is my controller showing that the showTaskDetailView value is true but my DOM isn't showing the ng-if="vm.ShowTaskDetailView"

How to bind a list of checkboxes in 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;
}

ng-class with multiple options

I'm fetching data using a REST API and one of the attributes returned can be any of 3 options;
The options are; Negative, Warning, Success.
I want to set a class using ng-class based on the value returned;
I'm able to do this but only for one;
Code below;
<div class="alert" ng-class="restaurantNotice(restaurant[0].notice)" ng-if="restaurant[0].notice.length">
<div class="alert-inner inner-large" ng-bind="restaurant[0].notice"></div>
</div>
$scope.restaurantNotice = function(a) {
return (a = Negative) ? 'negative' : '';
};
As you can see, if a = Negative then a class negative is applied else nothing is applied.
Now I want to check for all three options and apply 3 different classes respectively
Instead of function in ng-class, use object
ng-class="{'negative' : restaurant[0].notice == 'Negative', 'warning' : restaurant[0].notice == 'Warning', 'success' : restaurant[0].notice == 'Success'}"
You can try
<div class="alert" ng-class="{'negative' : restaurant[0].notice.length, 'warning' : restaurant[1].notice.length, 'success' : restaurant[2].notice.length}">
<div class="alert-inner inner-large" ng-bind="restaurant[0].notice"></div>
</div>
duplicate of Adding multiple class using ng-class
In this way:
<p ng-class="{a: deleted, b: important, c: error}">Example</p>
if a is true, apply class deleted, and so on.
If you are just going to set the same notice type (Negative, Warning, Success) as class then just convert to lower case and return from the function instead of putting conditions.
$scope.restaurantNotice = function(a) {
return a.toLowerCase();
};
OR
<div class="alert" class="{{restaurant[0].notice | lowercase}}" ng-if="restaurant[0].notice.length">

Difficulty adding multiple classes wit ng-class

I'm trying to add two classes to this div using ng-class, but even though checkForActive is returning true, it's being ignored and only class_{{$index}} is getting added.
If I remove class_{{$index}} altogether, active is added correctly.
Is there an obvious mistake in my syntax here?
<div "ng-class="{active: checkForActive, disabled: checkForDisable, class_{{$index}}} "></div>
You could just provide true value to the key class_{{$index}} just to that property gets added as a class name to the class list of the element. It is just the way you do active: checkForActive.
i.e
{active: checkForActive, disabled: checkForDisable, class_{{$index}} :true}
But i believe there could be some undesired behavior due the usage of interpolation ({{) within the ng-class directive (Atleast used to happen with older versions). So you could as well use an array.
ng-class="[checkForActive && 'active' , checkForDisable && 'disabled', 'class_' + $index]"
The above method will add a class name false if active or disabled is false, which should be harmless.
Or pass index to a controller function say getStatus($index) and return the object from there and use it in the ng-Class directive.
$scope.getClass = function(){
var obj = {active: $scope.checkForActive, disabled: $scope.checkForDisable};
obj['class_' + this.$index] = true;
return obj;
}
and
ng-class="getClass()"
#Okazari pointed out that it indeed works by mixing class with ng-class so you could also do:
class="class_{{$index}}" ng-class="{active: checkForActive, disabled: checkForDisable}"

using AND operator in Angular

I have the following HTML
<input type="checkbox" id="cbxSelectAllPreventive"/> <label>Select All</label>
<ul style="list-style: none;">
<li ng-repeat="test in lists.Tests">
</li>
</ul>
Test is an array of complex objects having isSelected property.
I want to use the checkbox as SelectAll functionality.
To do this , I need to supply ng-model to the checkbox, I can supply it as a method which checks in each of the tests and returns true/false. Is there any way to do this inline, without writing a method ?
I only see a way to do it using a function on ng-change
<input type="checkbox" id="cbxSelectAllPreventive"
ng-model="checked" ng-change="setAll(checked)"/>
...
$scope.setAll = function(isSelected){
$scope.lists.Tests.map(function(el){
el.isSelected = isSelected;
})
}
Working fiddle
EDIT:
For complete two-way connection between items' selection and check box the code will be a bit more complicated.
We will use an extra variable in $scope to reflect the label of check box. Don't forget to init the variable at controller creation
<label for="cbxSelectAllPreventive">{{selectLabel}}</label>
...
$scope.selectLabel = 'Select All';
setAll function should take care of setting this variable.
$scope.setAll = function(isSelected){
$scope.selectLabel = isSelected ? 'Deselect All' : 'Select All';
$scope.lists.Tests.map(function(el){
el.isSelected = isSelected;
})
}
And finally you definitely will have an option to select/deselect individual items. For this case you have to $watch your list. Mind the third parameter true which does deep comparison otherwise it won't "notice" changes inside objects.
$scope.$watch('lists.Tests', function(){
var text = $scope.lists.Tests.map(function(el){ return el.isSelected; }).join();
console.log(text);
var allSelected = $scope.lists.Tests.every(function(el){ return el.isSelected;});
var noneSelected = $scope.lists.Tests.every(function(el){ return !el.isSelected;});
if(noneSelected){
$scope.selectLabel = 'Select All';
$scope.checked = false;
}else if(allSelected){
$scope.selectLabel = 'Deselect All';
$scope.checked = true;
}
if(!noneSelected && !allSelected) {
$scope.selectLabel = 'Undetermined';
// here set the check box to undetermined (third) state
}
}, true);
Updated fiddle
Did you try ng-checkbox is should do exaclty what

Resources