How to use addClass method in angularjs - angularjs

I have an angularjs directive restricted to class. How can I add this by using addClass method in angularjs
directive
app.directive('number', function() {
return {
restrict: 'C',
link: function () {
}
};
});
code
<div id="test"></div>
I know it is possible by using jQuery like the following.
$( "#test" ).addClass( "number" );
Please help me in doing it by using angularjs

You don't need to use .addClass() angular provide ng-class directive to add class conditionally.
ng-class="{number:[condition]}"
it will add class number whenever your condition return true
yes but your directive will not be used by this I misunderstood your question previously.

You should add ng-class="yourClass" to element on view and add in your controller
$scope.yourClass = "your-new-class", not in directive

try this
link: function (lEmel) {
lElem.addClass("Foo");
}

Related

Run 'ng-click' inside a directive's isolated scope

Thanks in advance for taking the time to look into this question
I have serverside generated code that renders a directive wrapped around pre-rendered content.
<serverside-demo color="blue">
<p><strong>Content from Server, wrapped in a directive.</strong></p>
<p>I want this color to show: <span ng-style="{color: color}">{{color}}</span></p>
<button ng-click="onClickButtonInDirective()">Click Me</button>
</serverside-demo>
This means that 1.) the directive tag, 2.) the content inside the directive tag, 3.)the ng-click and 4.) The curly braces syntax are all generated by the server.
I want AngularJs to pick up the generated code, recompile the template and deal with the scope.
The problem is that I am having trouble getting it working. I understand that because the ng-click is inside the controller block, it is picked up not by the directive isolated scope, but the parent controllers. Instead I want the opposite... to pick up the onClickButtonInDirective scope function inside the serversideDemo link
I have created a jsfiddle best explaining my problem, which aims to clearly demonstrate the working "traditional" way of loading the template separately (which works) comparing it to the server-side way.
https://jsfiddle.net/stevewbrown/beLccjd2/3/
What is the best way to do this?
Thank you!
There are two major problem in your code
1- directive name and dom element not matched, - missing in dom element
app.directive('serverSideDemo', function() {
use <server-side-demo color="blue"> instead of <serverside-demo color="blue">
2- you need to compile the html code of server-side-demo dom with directive scope in link function
$compile(element.contents())(scope);
Working jsfiddle
Use templateUrl instead of template to fetch the content of directive from server:
app.directive('serverSideDemo', function() {
return {
restrict: 'AE',
scope: {
color: '='
},
templateUrl: 'link/that/returns/html/content',
link: function(scope, element, attrs) {
scope.onClickButtonInDirective = function() {
console.log('You clicked the button in the serverside demo')
scope.color = scope.color === 'blue' ? 'red' : 'blue';
}
}
};
});
Have a look at angular docs for more details

Move function from controller to directive

I have a function in my controller that manipulates the DOM. I understand this to be a bad practice and DOM manipulations should be moved into a directive. I'm having trouble pulling it out of the controller and into its own directive.
I have the following example code in my controller:
$scope.sidebarToggle = function() {
if ($scope.request = null) {
$(#container).switchClass('bottom', 'top', 400, 'linear');
$scope.editing = true;
}
else {
$(#container).switchClass('top', 'bottom', 400 'linear');
$scope.editing = false;
{
};
The above code's if conditions are very simplified, in the live code there are multiple conditions. Otherwise an ng-show/hide directive might have been possible.
The purpose of the code is to recognize the state the user is in, reveal/hide an off-screen sidebar (the class assignments), and set the 'editing' state of the controller.
How can this be refactored into a directive to accomplish the same goal?
Take a look at the documentation for angular directives to get started.
https://docs.angularjs.org/guide/directive
For 'angularising' the class of the container, use ng-class.
example # Adding multiple class using ng-class
You probably don't need to create your own directive for that.
Angular have already created some directives that could help you out.
In your case, you should use angular directive : ng-show and ng-class or ng-style
Exemple :
HTML
<div ng-show="request == null"> Edit </div>
<div ng-class="{'class-top': request == null,'class-bottom' : request != null}"> <div>
CSS :
.class-top{
...
}
.class-bottom{
...
}
Let me know if it works for you,
Nico
Try this:
app.directive('test', function() {
return {
restrict: 'E',
scope: {
},
link: sidebarToggle
};
});
I think it's creating a directive and link to your function sidebarToggle

Adding class to element using Angular JS

I know how to add a class on click of a button in 'jQuery'
$('#button1').click(function(){
$('#div1').addClass('alpha');
});
I want to achieve same thing by angular js. I have a controller - myController1. Can someone help me do it eazily?
AngularJS has some methods called JQlite so we can use it. see link
Select the element in DOM is
angular.element( document.querySelector( '#div1' ) );
add the class like .addClass('alpha');
So finally
var myEl = angular.element( document.querySelector( '#div1' ) );
myEl.addClass('alpha');
You can use ng-class to add conditional classes.
HTML
<button id="button1" ng-click="alpha = true" ng-class="{alpha: alpha}">Button</button>
In your controller (to make sure the class is not shown by default)
$scope.alpha = false;
Now, when you click the button, the $scope.alpha variable is updated and ng-class will add the 'alpha' class to your button.
Use the MV* Pattern
Based on the example you attached,
It's better in angular to use the following tools:
ng-click - evaluates the expression when the element is clicked (Read More)
ng-class - place a class based on the a given boolean expression (Read More)
for example:
<button ng-click="enabled=true">Click Me!</button>
<div ng-class="{'alpha':enabled}">
...
</div>
This gives you an easy way to decouple your implementation.
e.g. you don't have any dependency between the div and the button.
Read this to learn about the MV* Pattern
Try this..
If jQuery is available, angular.element is an alias for the jQuery function.
var app = angular.module('myApp',[]);
app.controller('Ctrl', function($scope) {
$scope.click=function(){
angular.element('#div1').addClass("alpha");
};
});
<div id='div1'>Text</div>
<button ng-click="click()">action</button>
Ref:https://docs.angularjs.org/api/ng/function/angular.element
First thing, you should not do any DOM manipulation in controller function.
Instead, you should use directives for this purpose. directive's link function is available for those kind of stuff only.
AngularJS Docs : Creating a Directive that Manipulates the DOM
app.directive('buttonDirective', function($timeout) {
return {
scope: {
change: '&'
},
link: function(scope, element, attrs) {
element.bind('click', function() {
$timeout(function() {
// triggering callback
scope.change();
});
});
}
};
});
change callback can be used as listener for click event.
querySelector is not from Angular but it's in document and it's in all DOM elements (expensive). You can use ng-class or inside directive add addClass on the element:
myApp.directive('yourDirective', [function(){
return {
restrict: 'A',
link: function(scope, elem, attrs) {
// Remove class
elem.addClass("my-class");
}
}
}
For Angular 7 users:
Here I show you that you can activate or deactivate a simple class attribute named "blurred" with just a boolean. Therefore u need to use [ngClass].
TS class
blurredStatus = true
HTML
<div class="inner-wrapper" [ngClass]="{'blurred':blurredStatus}"></div>
In HTML
To add the class named alpha, assign any variable like showAlpha to false first and then set it to true on click.
<div data-ng-class="{'alpha' : showAlpha}"> </div>
<button ng-click="addClass()"> </button>
In JS file
$scope.showAlpha = false;
$scope.addClass = function(){
$scope.showAlpha = true;
}
try this code
<script>
angular.element(document.querySelectorAll("#div1")).addClass("alpha");
</script>
click the link and understand more
Note: Keep in mind that angular.element() function will not find directly select any documnet location using this perameters
angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll()

AngularJS - Add attribute at runtime

I'm working on an AngularJS app. I'm trying to add the autofocus attribute to an element at runtime. The reason I want to do this is so I can set this attribute on one of several elements. How do you add an HTML attribute to an element via an AngularJS directive?
Thank you!
You can use the $set method on the $compile.directive.Attributes object. See the documentation here. This will create a new attribute which AngularJS will recognize. Remember to use the normalized (camelCase) version of the attribute. You can do it in the link function of your directive.
That's directive:
(function(){
angular.module('ng').directive('dynamicAutoFocus', function(){
return {
restrict: 'A',
link: function(scope, element, attrs){
scope.$watch(attrs.dynamicAutoFocus, function(id){
if(angular.isDefined(id)){
var target = document.getElementById(id);
if(target){
target.focus();
}
}
});
}
};
});
})();
Plunker

How do I add an ng-click to an element?

I have an HTML element that I cannot directly make changes to.
How would I add an ng-click event to it?
E.g.
<div id="myDiv"><img src="my/img/src/jpg"/></div>
How would I add an ng-click to the div? Jquery or vanilla JS answers, please.
Okay, I worked out that, as the element is being provided by a service, it doesn't exist on page load, so I have to try another way to do this.
The answer, in other circumstances, would be:
$("#myDiv").attr("ng-click", "myFunction()");
$compile($("#myDiv"))($scope);
Just make sure your element exists, when you try to add something to it!
If you're not restricted to using an ID on your element (...if you could use a class instead), then you could write a directive to bind the click handler.
You would write the directive to restrict it to that class:
<div class="myClass"><img src="my/img/src/jpg"/></div>
angular.module('myModule', [])
.directive('myClass', function () {
return {
restrict: 'C', // <-- restrict to classname
link: function (scope, el) {
el.on('click', function () {
// do stuff
})
}
};
})
This would bind a click to any element with myClass added to it.

Resources