Changing Element Colour on Hover AngularJS - javascript

So, I'm just getting started with angularjs and I'm already confused. I want to change the colour of a list element that corresponds to a hex code colour that is in an array. I've tried some stuff but I just can't get it.
Here's my code so far:
HTML
<div id="mainContentWrap" ng-app="newApp">
<div id="personContainer" ng-controller="personController">
<ul id="personList">
<li class="bigBox no_s" ng-style="personColour" ng-repeat="i in persons" ng-hover="changeColor()">< href="#/{{i.person_id}}">{{i.person_name}}</a></li>
</ul>
Javascript:
var app=angular.module('newApp',[]);
app.controller('personController',function($scope,$rootScope){
$rootScope.persons=[
{person_id:'0',person_name:'Jim',colour:"cc0000"},
{person_id:'4',person_name:'Bob',colour:"f57900"},
{person_id:'2',person_name:'James',colour:"4e9a06"},
{person_id:'9',person_name:'Paul',colour:"3465a4"},
{person_id:'3',person_name:'Simon',colour:"77507b"}
];
$scope.changeColor(){
$scope.personColour=$scope.persons.color// not sure what to do here???
}
});

There is no ng-hover directive. You'll want to use ng-mouseenter and ng-mouseleave.
Also, keep in mind that the syntax for ng-style is an object corresponding the CSS key-value pairs.
<li ng-repeat="i in persons" ng-style="personColour" ng-mouseenter="changeColor(i)"></li>
$scope.changeColor = function(person) {
$scope.personColour = {color: '#'+person.colour};
};
If you'd like for the color to change back to what it was before you hovered, you can create two functions, or pass a parameter to $scope.changeColour:
<li ng-repeat="i in persons" ng-style="personColour" ng-mouseenter="changeColor(i,true)" ng-mouseleave="changeColor(i,false)"></li>
$scope.changeColor = function(person, bool) {
if(bool === true) {
$scope.personColour = {color: '#'+person.colour};
} else if (bool === false) {
$scope.personColour = {color: 'white'}; //or, whatever the original color is
}
};
To take it a step further
You could create a directive for each person.
<person ng-repeat="i in persons"></person>
// your module, then...
.directive('person', [function() {
return {
restrict: 'E',
replace: true,
template: '<li class="bigBox no_s">{{i.person_name}}</li>',
link: function(scope, elm, attrs) {
elm
.on('mouseenter',function() {
elm.css('color','#'+i.colour);
})
.on('mouseleave',function() {
elm.css('color','white');
});
}
};
}]);

If you want to hack stay in the view:
<div ng-repeat="n in [1, 2, 3]" ng-style="{ 'background': (isHover ? '#ccc' : 'transparent') }" ng-mouseenter="isHover = true;" ng-mouseleave="isHover = false;">
<span>{{ n }}</span>
</div>

in the code bellow i add easy code to understand how to active style with condition. I hope that help you
<li ng-style="( (isOver == 'true') && (linkToActive == 'm1') ) ? { 'background-color': '#00bdcb' } : {'background-color': '#ededed'}"
ng-mouseenter="vm.changeColorMenu('m1','true')" ng-mouseleave="vm.changeColorMenu('m1','false')">
</li>
<li ng-style="( (isOver == 'true') && (linkToActive == 'm2') ) ? { 'background-color': '#00bdcb' } : {'background-color': '#ededed'}"
ng-mouseenter="vm.changeColorMenu('m2','true')" ng-mouseleave="vm.changeColorMenu('m2','false')">
</li>
</ul>
Javascript Code
function changeColorMenu(indexMenu,bool)
{
$scope.isOver = bool;
$scope.linkToActive = indexMenu;
}

If you check an example here you will see that ng-style directive waits for css style, not just value, so in your case it'll be:
$scope.person.colourStyle={'background-color':$scope.persons.color}
and in html it'll be:
<li class="bigBox no_s" ng-style="i.colourStyle" ng-repeat="i in persons" ng-hover="changeColor()">< href="#/{{i.person_id}}">{{i.person_name}}</a></li>
edit:
And You also need to set colour value to full hex for example: '#cc0000'.

In Angular, there is not ng-hover directive, so you should use ng-mouseenter & ng-mouseleave to simulate it.
<ul id="personList">
<li class="bigBox no_s" ng-style="personColour"
ng-repeat="i in persons" ng-mouseenter="changeColor($index)"
ng-mouseleave="recoverColor($index)">
{{i.person_name}}
</li>
</ul>
And you should use $index to get your element in persons Array
$scope.changeColor = function() {
$scope.personColour = { 'color': '#' + $scope.persons[$index].color };
// or 'background-color' whatever you what
}
$scope.recoverColor = function() {
$scope.personColour = {};
}

See Plunker Demo Here
Use ng-style to conditionally apply CSS styles - I've chosen to name this style 'personStyle'. Next, bind the ng-mouseover event to set the personStyle background-color to the person's colour attribute. Finally, bind the ng-mouseleave event to reset the personStyle when the mouse leaves the element. The changeColor() function is not needed for this solution to work.
<div id="personContainer" ng-controller="personController">
<ul id="personList">
<li class="bigBox no_s" ng-repeat="i in persons" ng-style="personStyle">
<a href="#/{{i.person_id}}" ng-mouseleave="personStyle={}"
ng-mouseover="personStyle={ 'background-color':'#' + i.colour}">
{{i.person_name}}</a>
</li>
</ul>
</div>

Related

How to get element by id which is dynamically created by ng-repeat in angularjs

I am only posting the necessary code and solving this much will clear rest of my doubts. I am new to angularjs, so kindly forgive if I am asking something stupid.
I am using ng-repeat to generate a list which uses an array defined in the controller scope. When I click on 'Add Another' button, a new element is created. I want to get access of this element to add a class to it. But when I use 'getElementById' function in the same function 'addNewForm' I get 'null'.
However, when I call function 'fn' by hitting 'Find Untitled' button, I get the correct element. Could anybody explain and solve this? Any help is appreciated. Thanks in advance!
I am posting the code below:
HTML:
<div ng-controller="myctrl3">
<ul id ="menu_Ul">
<li ng-repeat="x in list">
<button id="{{ 'navAppsButtonID-' + $index }}">{{x}}</button>
<br>
</li>
<li>
<button ng-click="addNewForm()">Add another</button>
</li>
</ul>
<button ng-click="fn()">Find Untitled</button>
</div>
JS:
.controller("myctrl3", function($scope) {
var list = ['abcd', 'efgh', 'ijkl', 'mnop'];
$scope.list = list;
$scope.abc = function () {
var listPush = function () {
$scope.list.push("Untitled Menu");
for(var i = 0;i<$scope.list.length-1;i++) {
var element = document.getElementById('navAppsButtonID-'+i);
element.classList.remove('current');
}
};
var listLen = $scope.list.length;
if($scope.list[listLen-1] === undefined) {
listPush();
}
else if ($scope.list[listLen-1] == "Untitled Menu") {
alert("Cannot open more than one Untitled Menu at the same time.");
}
else {
listPush();
}
};
$scope.addNewForm = function() {
$scope.abc();
console.log("Element is: ", document.getElementById('navAppsButtonID-'+($scope.list.length-1)));
};
$scope.fn = function () {
console.log("Element is: ", document.getElementById('navAppsButtonID-'+($scope.list.length-1)));
};
})
You're thinking too much jQuery and too little angular. If the goal is to add a class to the last element of ng-repeat, this is how you do that:
<li ng-repeat="x in list">
<button ng-class="{ current: $last }">{{ x }}</button>
</li>
$last is a variable available inside ng-repeat, and if it's true, ng-class will set the class current on the element.
You don't assign unique ids to elements to getElementById from somewhere else when working in angular.

AngularJs toggling function for selected item in ng-repeat

I have a list of items, and I have enable/disable method as an option for each item in a list.
I want to toggle only one item in a list:
Current implementation toggles all items in a list, and changes class icons for all.
HTML
<div class="device" ng-repeat="item in items" ng-class="{'open': item.isOpen}">
<!-- Enable/Disable-->
<a href="#" class="m-r-20" ng-click="test.toggleMethod(item.Id)">
<span class="{{test.buttonClassIcon}}" title="{{test.title}}"></span>
</a>
</div>
Controller
model.enabled = true;
model.toggleMethod = function (deviceId) {
if (model.enabled) {
locationService.start(deviceId).then(deviceList);
} else {
locationService.stop(deviceId).then(deviceList);
}
model.enabled = !model.enabled;
model.buttonClassIcon = model.enabled ? 'fa fa-bell' : 'fa fa-bell-slash';
model.title = model.enabled ? 'Enable' : 'Disable';
};
When I click bell, it changes class to all, and toggles global variable.
You should have an enabled property for each element in the list.
model.items.map(function(item){
item.enabled = false; // or other default value
});
and the in the html :
<a href="#" class="m-r-20" ng-click="test.toggleMethod(item)">
<span ng-if="item.enabled" class="fa fa-bell" title="Enable"></span>
<span ng-if="!item.enabled" class="fa fa-bell-slash" title="Disable"></span>
</a>
or you can use ng-class or create functions like getTitle(item.enabled) which returns the corresponding title.
and the toggleMethod:
model.toggleMethod = function (device) {
var deviceId = device.Id;
if (device.enabled) {
locationService.start(deviceId).then(deviceList);
} else {
locationService.stop(deviceId).then(deviceList);
}
device.enabled = !device.enabled;
};
Here is the fiddle.
Hope this is what you were trying to achieve.
Inside your function you dont enable/disable the selected item , instead you enable/disable a model object.
I am going to make an assumption , according to your snippet.
Since you have the item id or you can pass the $index(the position into the items array) you could do :
//also pass $index into ng-click function
<span class="{{test.buttonClassIcon}}" title="{{test.title}}"></span>
and into function body check the selected item:
model.toggleAlarmMethod = function (deviceId,indx) {
if ($scope.items[indx].enabled) {
locationService.start(deviceId).then(deviceList);
} else {
locationService.stop(deviceId).then(deviceList);
}
//enable/disable selected item
$scope.items[indx].enabled = !$scope.items[indx].enabled;
$scope.items[indx].buttonClassIcon = $scope.items[indx].enabled ? 'fa fa-bell' : 'fa fa-bell-slash';
$scope.items[indx].title = $scope.items[indx].enabled ? 'Enable' : 'Disable';
};

Doesn't work two ways of filtering (AngularJS)

I'm trying to make two ways of filtering (via clicking on letters or via typing in input field).
<body ng-controller="MainController">
<ul search-list=".letter" model="search">
<li class="letter" ng-repeat="letter in alphabet.letter">{{ letter }}</li>
</ul>
<div class="container" ng-controller="CountriesController">
<input id="q" type="text" ng-model="search " />
<ul>
<li ng-repeat="country in countries.country | filter:search:startsWith">{{ country }}</li>
</ul>
</div>
</body>
and js:
var app = angular.module('demo', []);
var controllers = {};
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
app.directive('searchList', function() {
return {
scope: {
searchModel: '=model'
},
link: function(scope, element, attrs) {
element.on('click', attrs.searchList, function() {
scope.searchModel = $(this).text();
scope.$apply();
});
}
};
});
controllers.MainController = function($scope) {
$scope.setTerm = function(letter) {
$scope.search = letter;
};
$scope.alphabet = {
letter: alphabet
}
};
controllers.CountriesController = function($scope){
$scope.countries = {
country:['Ukraine','Urugvai','Russia','Romania','Rome','Argentina','Britain']
}
$scope.startsWith = function (actual, expected) {
var lowerStr = (actual + "").toLowerCase();
return lowerStr.indexOf(expected.toLowerCase()) === 0;
}
};
app.controller(controllers);
On first look everything is working fine, but it is so only on first look...
When at first I click on any letter - filter works good.
When then I'm typing in input field - filter works good.
But after I typed in input field or delete text from there via 'backspace' button - filter by clicking on letters stops working...
Why it works like this and how I can fix this issue?
Here is my DEMO
Thanx in advance!
The problem fount for using two controler's. If you remove CountriesController , then everything working good.
The Search values was confused with which controller using that scope object.I think you don't need implement two controller for this scenario
See the working demo if you remove CountriesController.
change this part of html to this it works fine (ng-model="$parent.search ")
<div class="container" ng-controller="CountriesController">
<input id="q" type="text" ng-model="$parent.search " />
<ul>
<li ng-repeat="country in countries.country | filter:search:startsWith">{{ country }}</li>
</ul>
</div>

ng-Include: evaluator function never called

HTML:
<section ng-controller="NavigationController as navCtrl">
<ul>
<li ng-click="navCtrl.setNav(1)" ng-class="{ 'myApp_nav_items_selected': navCtrl.isNavPage(1) , 'myApp_nav_items': !navCtrl.isNavPage(1) }"><a ng-class="{ 'myApp_nav_selected_a': navCtrl.isNavPage(1) , 'myApp_nav_a': !navCtrl.isNavPage(1) }" href="#">Option 1</a></li>
<li ng-click="navCtrl.setNav(2)" ng-class="{ 'myApp_nav_items_selected': navCtrl.isNavPage(2) , 'myApp_nav_items': !navCtrl.isNavPage(2) }"><a ng-class="{ 'myApp_nav_selected_a': navCtrl.isNavPage(2) , 'myApp_nav_a': !navCtrl.isNavPage(2) }" href="#">Option 2</a></li>
<li ng-click="navCtrl.setNav(3)" ng-class="{ 'myApp_nav_items_selected': navCtrl.isNavPage(3) , 'myApp_nav_items': !navCtrl.isNavPage(3) }"><a ng-class="{ 'myApp_nav_selected_a': navCtrl.isNavPage(3) , 'myApp_nav_a': !navCtrl.isNavPage(3) }" href="#">Option 3</a></li>
</ul>
<div class="myAppta_page">
<div ng-include="navCtrl.getPage()"></div>
</div>
</section>
JS
tripdataApp.controller('NavigationController', function ($scope) {
this.$scope = $scope;
this.$scope.navPage =1;
this.setNav = function(theNavPage) { <--- WORKS OK
console.log("set nav " + theNavPage);
this.$scope.navPage = theNavPage;
console.log("nav IS set to " + this.$scope.navPage);
};
this.isNavPage = function(checkNavPage) { <---- WORKS OK
return this.$scope.navPage === checkNavPage;
};
this.getPage = function() { <---- NEVER CALLED
console.log("-=-=-=-=- nav IS set to " + this.$scope.navPage);
switch (this.$scope.navPage)
{
case 1:
console.log("dashboard");
return "#/pages/dashboard.php";
break;
default:
console.log("ddefault");
return "#/pages/unimplemented.php";
break;
}
}
});
What am I doing wrong?
As per I can see in the docs, there is no reference saying that you can evaluate a controller method within an ng-include directive. Other than that, it does say that you can use a constant but you have to add single quotes wrapping up the content of the ng-include.
For more info https://docs.angularjs.org/api/ng/directive/ngInclude
I think a different approach is the solution for this issue.

AngularJS directive - ng-class in ng- repeat should it be a $watcher to toggle style?

I am currently implementing a spike to further my understanding on angular directives etc.
The premise is to create a FX watch list on a number of currency pairs.
My data feed is set up for my price updates via socket.io.
The stumbling block that i have is being able to change the css dependent on price change ie up arrow for up, down arrow for down.
I feel a watcher function is what i need but struggled on where to start so was looking for some sort of expression in ng-class to do the job ... but the method not only started to look like a $watcher it was also flawed as saving the previous price to scope on my directive meant there was only ever one old value not one for each price.
There for my question is : Is the solution with ng-class or in setting up a $watcher function ?
Heres my code ...
HTML template
<div ng-repeat="rate in rates" ng-click="symbolSelected(rate)">
<div class="col-1-4">
{{rate.symbol}}
</div>
<div class="col-1-4">
<span ng-class='bullBear(rate.bidPoint)' ></span> {{rate.bidBig}}<span class="point">{{rate.bidPoint}}</span>
</div>
<div class="col-1-4">
<span ng-class='bullBear(rate.offerPoint)' ></span> {{rate.offerBig}}<span class="point">{{rate.offerPoint}}</span>
</div>
<div class="col-1-4">
{{rate.timeStamp | date : 'hh:mm:ss'}}
</div>
</div>
My directive currently looks like this ... as noted this will not work and the bullBear method was starting to look like a $watcher function.
.directive('fxmarketWatch', function(fxMarketWatchPriceService){
return {
restrict:'E',
replace:'true',
scope: { },
templateUrl:'common/directives/fxMarketWatch/marketwatch.tpl.html',
controller : function($scope, SYMBOL_SELECTED_EVT,fxMarketWatchPriceService){
$scope.symbolSelected = function(currency){
$scope.$emit(SYMBOL_SELECTED_EVT,currency);
}
$scope.bullBear = function(newPrice){
if ($scope.oldPrice> newPrice ){
return ['glyphicon glyphicon-arrow-down','priceDown'];
}
else if ($scope.oldPrice > newPrice ){
return ['glyphicon glyphicon-arrow-up','priceUp'];
}
}
$scope.$on('socket:fxPriceUpdate', function(event, data) {
$scope.rates = data.payload;
});
}
}
})
You could modify the ng-class and move the logic into the view, because styling and placing classes shouldn't be done in code.
<div class="col-1-4">
<span class="glyphicon" ng-class="{'glyphicon-arrow-up priceUp': oldPrice > rate.bidPoint, 'glyphicon-arrow-down priceDown':oldPrice > rate.bidPoint}"></span> {{rate.bidBig}}<span class="point">{{rate.bidPoint}}</span>
</div>
Or like this:
<span class="glyphicon {{oldPrice > rate.bidPoint ? 'glyphicon-arrow-down priceDown':'glyphicon-arrow-up priceUp'}}></span> {{rate.bidBig}}<span class="point">{{rate.bidPoint}}</span>
I will recommend you to use both ng-class and $watcher. The two can actually compliment each other:
UPDATE: To make the code works with ng-repeat, we need to migrate all of CSS classes logic to another controller:
app.controller('PriceController', function($scope) {
// we first start off as neither up or down
$scope.cssBid = 'glyphicon';
$scope.cssOffer = 'glyphicon';
var cssSetter = function(newVal, oldVal, varName) {
if (angular.isDefined(oldVal) && angular.isDefined(newVal)) {
if (oldVal > newVal) {
$scope[varName] = 'glyphicon glyphicon-arrow-down priceDown';
} else if (newVal > oldVal) {
$scope[varName] = 'glyphicon glyphicon-arrow-up priceUp';
} else {
$scope[varName] = 'glyphicon';
}
}
};
// watch for change in 'rate.bidPoint'
$scope.$watch('rate.bidPoint', function(newVal, oldVal) {
cssSetter(newVal, oldVal, 'cssBid');
});
// watch for change in 'rate.offerPoint'
$scope.$watch('rate.offerPoint', function(newVal, oldVal) {
cssSetter(newVal, oldVal, 'cssOffer');
});
});
Next, we bind this PriceController onto ng-repeat div. By doing so, Angular will create one controller instance for each rate in rates. So this time rate.bidPoint and rate.offerPoint should be available for $watch-ing:
<div ng-repeat="rate in rates" ng-click="symbolSelected(rate)" ng-controller="PriceController">
<div class="col-1-4">
<span ng-class='cssBid'></span> {{rate.bidBig}}<span class="point">{{rate.bidPoint}}</span>
</div>
<div class="col-1-4">
<span ng-class='cssOffer'></span> {{rate.offerBig}}<span class="point">{{rate.offerPoint}}</span>
</div>
</div>
Now, directive's controller will be much shorter than before:
controller: function($scope, SYMBOL_SELECTED_EVT, fxMarketWatchPriceService){
$scope.symbolSelected = function(currency) {
$scope.$emit(SYMBOL_SELECTED_EVT, currency);
}
$scope.$on('socket:fxPriceUpdate', function(event, data) {
$scope.rates = data.payload;
});
}

Categories

Resources