how to change classes of html elements obtained from ng-click() - javascript

I have an html element as :
<i ng-click="run()"></i>
and in my controller:
$scope.run() = function($event) {
var el = $event.currentTarget;
}
now how can i want to add some classes on the el element but el.addClass('class-name') is not working
I can only use javascript here not jquery

ng-class="expression"
Its recommended that you use ng-class instead of using controller to add class.
but you can use element.classList.add('className') also if you want

When modifying classes on elements using the classList API you need to use the classList namespace. i.e.
el.classList.add('class-name');
It looks like you are still thinking in jQuery.

html:
<i ng-click="run($event)"></i>
JS:
$scope.run() = function(event) {
var element = angular.element(event.currentTarget);
element.addClass('new');
}

You can use ng-class here is the demo Jsfiddle demo
Js code
var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
$scope.myClass = false;
$scope.addClass = function() {
$scope.myClass = true;
}
});
HTML
<div ng-app="app">
<div ng-controller='ctrl'>
<span ng-class='{myClass:myClass}'>This my content</span>
<button ng-click='addClass()'>
Add class
</button>
</div>
</div>

I think a more propriate way to do it, is to use ng-class for your i element, and bind it to some variable on your scope.
Example:
Your HTML:
<i ng-click="changeClass()" ng-class="myClass"></i>
Your Angular controller:
function Controller($scope){
$scope.myClass = "";
$scope.changeClass = function() {
$scope.myClass = //Put here your CSS class
}
}

You can use ng-class in Angular js
<i ng-class="myclass" ng-click="run()"></i>
in controller
$scope.run() = function(event) {
$scope.myclass="classname";
}

Simply add like this,in HTML
<i ng-click="run($event)">i</i>
In contoller
$scope.run = function($event) {
$event.target.classList.add("className")
}

Related

AngularJS - Repeating a div and a button

I want to use ng-repeat to repeat a div. This div also has a button within it.
Currently, I'm doing it by creating the div and the button in the javascript part and pushing the final result in an array :
var newDiv = document.createElement('div');
var newButton = document.createElement('button');
newDiv.appendChild(newButton);
$scope.arrayDiv.push(newDiv);
I have 2 questions :
1) What should be the html syntax ? Is the following correct ?
<div id='main_chart_div' ng-repeat="x in arrayDiv" value={{x}}></div>
2) Is there a way to do that without manipulating the DOM ?
You can have the button in your template:
<div id='main_chart_div' ng-repeat="x in arrayDiv" value={{x}}>
<button></button>
</div>
By the way, you shouldn't repeat an element with a static id.
One possible way is to use ng-bind-html within ng-repeat.
ng-bind-html evaluates the expression and inserts the resulting HTML into the element in a secure way.
Secure way is with either ngSanitize or make use of $sce. Demo
Filter directive for safe binding:
app.filter('safeHtml', function ($sce) {
return function (val) {
return $sce.trustAsHtml(val);
};
});
View :
<div id='main_chart_div' ng-repeat="x in arrayDiv">
<p ng-bind-html="x.html | safeHtml"></p>
</div>
Controller:
$scope.arrayDiv = [{html: '<h1>Heading</h1>'}];
var newDiv = document.createElement('div');
var newButton = document.createElement('button');
newButton.innerHTML = "Button";
newDiv.appendChild(newButton);
$scope.arrayDiv.push({html : newDiv.outerHTML});

Get the background color of div - AngularJs?

I want to get the background color of a DIV element when I click on that div.
HTML -
<div style="background-color:red" ng-click="getFilter($event)" class="agenda col-md-4">ABCDEGF/div>
JS Controller -
$scope.getFilter = function(event){
};
If we do in in jQuery, It would have been done as -
$('div').click(function(){
$color = $(this).css('background-color');
});
But I want to do with angularJs. Someone help ?
you can use:
$scope.getFilter = function(event) {
$scope.color = $(event.currentTarget).css('background-color');
};
You could use ng-style for setting color dynamically, I'd just have it inside the API response for each record. I assumed that you are rendering all the elements using ng-repeat directive.
Markup
<div ng-repeat="item in items"
ng-style="{'background-color': item.color}"
ng-click="getFilter(item);"
class="agenda col-md-4">
ABCDEGF
</div>
Code
$scope.getFilter = function(item){
$color = item.color;
}
Created sample example with service to get and assign color dynamically. JSFiddle - https://jsfiddle.net/q16fcq99/
Modify the service with your required call. Hope this will help.
<body ng-app="SampleApp">
<div ng-controller="fcController">
<div ng-style="{'background-color': divColor}" ng-click="getFilter($event);" class="agenda col-md-4">
ABCDEGF
</div>
</div>
</body>
var sampleApp = angular.module("SampleApp", []);
sampleApp.controller('fcController', function($scope, colorService) {
$scope.divColor = 'red';
$scope.getFilter = function(event) {
$scope.divColor = colorService.getColor();
console.log('Event Fired');
};
});
sampleApp.service('colorService', function() {
this.getColor = function() {
return "blue"; //Call Actual Service to Get Color
};
});

Ng-class removing class when click event

I have a button on main page that link to some another page. When that button clicked I want to remove class from one div.
Controller:
$scope.myClass = ["container","gnc1"];
$scope.removeClass = function() {
$scope.myClass.splice(1, 2);
}
I am using ui-router for this:
<body ui-view="viewA">
<div ng-class="myClass">
<div ui-view="viewC">
<div ui-view="viewB">
<a ui-sref="B"> </a> //Loads the B.html to where viewB is. ControllerB
<a ui-sref="C" ng-click="removeClass()"> </a> //Loads the C.html where viewC is. controllerC
</div>
</div>
</div>
</body>
Button:
<a ng-click="removeClass()"></a>
What am I missing here? How can I remove that "gnc1" class?
Edit-1:
<div ng-class="{container:dogru, gnc1:yanlis}">
indexCtrl:
$scope.dogru = true;
$scope.yanlis = true;
Button belongs to controllerC so in controllerC:
$scope.removeClass = function($scope) {
$scope.dogru = true;
$scope.yanlis = false;
}
But this didnt work either. What am i missing?
I suggest you use ng-class like this instead
<div ng-class="{container:isConditionTruthy, gnc1:!isConditionTruthy}">
...ng-click="isConditionTruthy = !isConditionTruthy"...
If you post a fiddle with your code I can show you.
Just pop the element out, since the item you want to remove is at the end of the array.
myClass = ["container","gnc1"];
removeLast = function() {
myClass.pop();
}
removeLast();
console.log(myClass);

How to change attribute of html in angular js?

I want to change attribute of a div in angularjs. I know how to do in jquery but not in angular.
html :
<div ng-app="test">
<div ng-controller="cont">
<button ng-click="updateStatus()">TOGGLE ATTRIBUTE </button>
<div id="test" {{status}}>TEXT </div>
</div>
</div>
js :
var angApp = angular.module('test',[]);
angApp.controller('cont', ['$scope', function($scope){
$scope.status = 'someattr';
$scope.updateStatus = function() {
if( $scope.status == 'someattr'){
$scope.status = '';
}else{
$scope.status = 'someattr';
}
};
}])
Here is jsfiddle to work with.
In jquery :
var div = $('#test');
$('button').on('click',function(){
if( div.attr('someattr'){
div.removeAttr('someattr');
}else{
div.attr('someattr',true);
}
})
I want to achive same in angularjs.
NOTE : I AM NOT TRYING TO ADD DISABLED STATE TO DIV. I JUST WANT TO TOGGLE AN ATTRIBUTE.
In your specific case (add disabled attribute), you have to use ng-disabled in order to bind its value to a $scope variable.
It makes no sense to use it on a div, I'll use a button instead to give you an example:
<button ng-click="updateStatus()">TOGGLE ATTRIBUTE </button>
<button id="test" ng-disabled='status'>TEXT</button>
see a working example HERE
UPDATE
To toggle an attribute, yo can use attr() and removeAttr():
el.attr("disabled", "true");
el.removeAttr("disabled");
See a complete example HERE
NOTE (thanks to jme11): as reported on Angular Dev Guide
Do not use controllers to:
Manipulate DOM — Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.
you should avoid to manipulate the DOM inside the controller.
Make a directive which uses .attr and .removeAttr in a $watch handler. Here's a modified version of your fiddle: http://jsfiddle.net/0eqz1qo1/1/
The directive:
.directive('addAttr', function() {
return function(scope, elem, attr) {
scope.$watch(attr.addAttr, function(val, prev) {
if(val)
elem.attr(val, "");
if(prev && prev !== val)
elem.removeAttr(prev);
});
}
})
Usage:
$scope.myVar = 'hello';
...
<div add-attr="myVar"></div>
becomes:
<div add-attr="myVar" hello></div>
You can not implement disable property for any div.But you can hide or show the div using Angular.js.Check the code below.
<div ng-app="test">
<div ng-controller="cont">
<button ng-click="updateStatus()">TOGGLE ATTRIBUTE </button>
<div id="test" ng-hide="hide-div" >TEXT </div>
</div>
</div>
JS:
var angApp = angular.module('test',[]);
angApp.controller('cont', ['$scope', function($scope){
$scope.hide-div = true;
$scope.updateStatus = function() {
if( $scope.hide-div == true){
//do something here
}else{
$scope.hide-div = true;
}
};
}])
Other option is you can also use ng-class in div and inside those class you can declare display:none,display:block
You can't add an attribute by this way with angularJS. If you inspect your code, you can see that the attribute that you're trying to pass in div is {{status}}(your expression), use existing attributes rather than create your own! For example: ng-disabled, ng-show, ng-hide.
It's not really right thing to do. I guess, cannot inject attribute with angularJS. {{status}} is an expression, it's like expression and will evaluate by angularjs while rendering to html. about expression: https://docs.angularjs.org/guide/expression
Replace your line :
<div id="test" {{status}}>TEXT </div>
with these :
<div id="test" someattr="" ng-if="status=='someattr'" >TEXT</div>
<div id="test" ng-if="status==''" >TEXT</div>

Change text color dynamically AngularJS

I struggle thinking "The Angular Way" so this is undoubtedly a simple problem, but I'm trying to have it so when I click a button (which will eventually be colored) the text changes to that color. Here is essentially the code:
JS
var myApp = angular.module('myApp', []);
myApp.controller('ColorCtrl', ['$scope', function($scope){
$scope.changeColor = function(value){
return {"color:" value };
}
$scope.turnGreen = function (){
//what to do here?
}
$scope.turnBlue = function() {
//and here?
}
}]);
HTML
<div ng-app="myApp" ng-controller="ColorCtrl">
<button ng-click="turnBlue()">Make text blue</button>
<button ng-click="turnGreen()">Make text green</button>
<p ng-style="changeColor(value)">I should be either green or blue!</p>
</div>
I know I could easily use jQuery to select the text I want to work with, but I don't want to do that. Do i need to give my paragraph a model? Any push in the right direction is greatly appreciated - thank you.
You could do this way:
Define ng-class directive and value as colorClass which will be set in the scope.
<p ng-class="customStyle.colorClass">I should be either green or blue!</p>
and do:
$scope.customStyle = {};
$scope.turnGreen = function (){
$scope.customStyle.colorClass = "green";
}
$scope.turnBlue = function() {
$scope.customStyle.colorClass = "blue";
}
and some rules:
.green{
color:green;
}
.blue{
color:blue;
}
or with inline style
<p ng-style="customStyle.style">I should be either green or blue!</p>
and
$scope.customStyle = {};
$scope.turnGreen = function (){
//what to do here?
$scope.customStyle.style = {"color":"green"};
}
$scope.turnBlue = function() {
$scope.customStyle.style = {"color":"blue"};
}

Categories