AngularJS ng-class the same class with different conditions - angularjs

I have a option in the back-end to let user change icon in default and in hover state. This is the code
ng-class="{'{{getAnswerButtonHoverIcon()}}':hovering, '{{getAnswerButtonIcon()}}' : !hovering}
But the problem is, when the user selected the same icon for default state and hover state, like for example they have selected "fa-circle-o" the output of the HTML will be
ng-class="{'fa-circle-o':hovering, 'fa-circle-o' : !hovering}"
and it doesn't work anymore. When I try to test it out, it removes the "fa-cricle-o" class on hover. Any idea why is it happening? And if you can suggest better solution, it will be greatly appreciated. Thanks!

I mentioned in a comment that I would probably have a single function but I think I misunderstood your question at first. Building on Joshua's approach here is something that could work for you: if the two functions return the same value then it still works.
I feel that this is not the nicest solution since it is generating a string into a class, but the same can be changed to ng-class and {hovering ? sg() : sgelse()} as value. I hope it shows you a way to handle these kind of interactions.
Let me know if it does/doesn't work so that we could further help you.
var app = angular.module("mainModule",[]);
app.controller("mainCtrl", function($scope){
$scope.icon = {};
$scope.icon.hovering = false;
$scope.getAnswerButtonHoverIcon = function(){
return 'bluebg';
};
$scope.getAnswerButtonIcon = function(){
return 'redbg';
};
});
.bluebg{background-color:blue}
.redbg{background-color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="mainModule">
<div ng-controller="mainCtrl">
<div class="{{ icon.hovering ? getAnswerButtonHoverIcon() : getAnswerButtonIcon() }}"
ng-mouseenter="icon.hovering = true" ng-mouseleave="icon.hovering = false">
<p>I have different backgrounds</p>
</div>
</div>
</div>

You can also use the ng-class like this, which will just apply the class the function outputs:
ng-class="(hovering ? '{{getAnswerButtonHoverIcon()}}': '{{getAnswerButtonIcon()}}')

Related

ngRepeat doesn't refresh rendered value

I'm having an issue with ngRepeat :
I want to display a list of students in two different ways. In the first one they are filtered by group, and in the second they are not filtered.
The whole display being quite complex, I use a ngInclude with a template to display each student. I can switch between view by changing bClasseVue, each switch being followed by a $scope.$apply().
<div ng-if="currentCours.classesOfGroup !== undefined"
ng-show="bClassesVue">
<div ng-repeat="group in currentCours.classesOfGroup">
<br>
<h2>Classe : [[group.name]]</h2>
<div class="list-view">
<div class="twelve cell"
ng-repeat="eleve in group.eleves | orderBy:'lastName'"
ng-include="'liste_eleves.html'">
</div>
</div>
</div>
</div>
<div class="list-view" ng-show="!bClassesVue">
<div class="twelve cell"
ng-repeat="eleve in currentCours.eleves.all"
ng-include="'liste_eleves.html'">
</div>
</div>
My problem happens when my list of students change (currentCours here). Instead of refreshing the ngRepeat, both lists concatenate, but only in the unfiltered view.
I tried adding some $scope.$apply in strategic places (and I synchronize my list for example) but it doesn't help.
EDIT : the function used to refresh currentCours in the controller. It's called when a "cours" is selected inside a menu.
$scope.selectCours = function (cours) {
$scope.bClassesVue = false;
$scope.currentCours = cours;
$scope.currentCours.eleves.sync().then(() => {
if ($scope.currentCours.classe.type_groupe === 1) {
let _elevesByGroup = _.groupBy($scope.currentCours.eleves.all, function (oEleve) {
return oEleve.className;
});
$scope.currentCours.classesOfGroup = [];
for(let group in _elevesByGroup) {
$scope.currentCours.classesOfGroup.push({
name: group,
eleves: _elevesByGroup[group]
});
}
$scope.bClassesVue = true;
}
});
utils.safeApply($scope);
};
Well, I found a workaround, but I still don't know why it didn't work, so if someone could write an explanation, I would be very thankful.
My solution was simply to open and close the template each time I switch between views.

ng-class set class name from dynamic value and add extra conditions

I was looking for the syntax to add classname from a value.
Just before giving up ,i found here an answer that works.
Now the problem is you can't add , like you would normally and add more conditions.
What would be the correct syntax for Ex2 to work?
Ex1: This works:
ng-class="{'{{obj.status}}' : obj.status}"
Ex2: This doesn't work: (also no error in the console)
ng-class="{'{{obj.status}}': obj.status, 'isEmployee': status == 'isEmployee'}"
Update:
I didn't change anything relevant any now it works >< Give me some time to figure out what the hell is going on ...
I know what i did to make it work. I was trying to change something else and i added this to the controller that made it work, because it's basically the same data :
$scope.status= obj.status
This would be the solution in my case.
Copy/Pasted the exact code for the button, since you all say it should work. Can you spot something wrong with it?
<md-button ng-class="{'{{editedObject.interviewStatus}}' : editedObject.interviewStatus, 'isEmployee': interviewStatus == 'isEmployee'}" aria-label="OpenStatusMenu" ng-click="$mdMenu.open($event)">
please check your obj and status value it's look like this?
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http,$q) {
$scope.obj = {
"status":"abc"
}
$scope.status = "isEmployee";
});
.abc{
color: blue;
}
.isEmployee{
background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<span ng-class="{'{{obj.status}}': obj.status, 'isEmployee': status == 'isEmployee'}">both class added</span>
</div>
A comma should work. You might have forgotten the " at the end?

value of progressbar doesnt work

theres my progress bar code:
<div class="col-sm-4" ng-repeat="var in payloadNbrMissionParStatut">
<h4 class="no-margin">{{var.number}}</h4>
<progressbar value={{tom}} class="progress-xs no-radius no-margin" type={{gg}} ng-if="var.des=='Clos' ? gg='danger' : var.des=='En cours'? gg='warning' :gg='info' " ></progressbar>
{{var.des}}
</div>
the problem is in the value: when i populate it with static data it works good, but when i populate wit data come from the controller it doesnt work.
var is a reserved JS keyword. As errors inside directive expressions are silent, you aren't seeing any alerts because it's simply being ignored. Change var to something else and it should work.

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.

ng repeat not updating

Hi I am a newbie to angular js and I am hoping someone can help me out with the following problem.
I have a numeric field called numAdults and I need to show a set of field (such as name, address, telephone etc ) numAdult times to get those information for each of those person.
Here is the jsfiddle for the problem jsfiddle link
Here is also an overview of code of the controller
function bookingController($scope){
$scope.numAdults = 1;
$scope.personLoop = function(){
console.log('personLoop called')
return new Array($scope.numAdults);
//return new Array(2);
}
the html
<label for="book_num_adults">Number of adults:</label>
<input id="book_num_adults" type="text" ng-model="numAdults">
<div class="row" ng-repeat="t in personLoop()" style="border:2px solid red;margin-top:10px">
<h4>Person {{$index+1}}</h4>
<input placeholder="name"><br>
<input placeholder="address"><br>
<input placeholder="telephone"><br>
</div>
Can you also help me with how to transform this as an module ( not just a controller based )
Thank you in advance!
Your Fiddle was riddled with errors...
http://jsfiddle.net/bRgTR/5/
Under Frameworks & Extensions, you need to change the 2nd dropdown from "onLoad" to one of the "No wrap" options
Your controller definition is mangled. It's supposed to be: .controller('name', ['depname', function (depname) { })]); -- you had your closing array misplaced.
You should really use semi-colons.
You don't create an array of 5 items in JavaScript like this: var a = new Array(5), that creates an array that contains a 5. Instead, you should do var a = []; a.length = 5;

Resources