Angular ng-click event delegation - angularjs

So if i have a ul with 100 li's should there be ng-clicks in each li or is there a way to bind the event to the ul and delegate it to the li's kind of what jquery does? Would this be better or worse? Are we having 100 events or is it just one event in the end?

It seems angular doesn't do event delegation with repeaters. Someone opened an issue on github about it. The argument is if it actually leads to better performance.
There might be a workaround but it would require jQuery. It consists of creating a special directive to be used on a parent element and register the listener on its dom node.
Here's an example, that is passed a function name to be called when a children node is clicked, and is also passed a selector to help identify which children nodes to listen to.
Since angular's jquery implementation only gives us the bind method - which is limited to registering event listeners to the actual element - we need to load jQuery to have access to either the on or delegate method.
HTML
<ul click-children='fun' selector='li'>
<li ng-repeat="s in ss" data-index="{{$index}}">{{s}}</li>
</ul>
The function defined is defined in the controller and it expects to be passed an index
$scope.fun = function(index){
console.log('hi from controller', index, $scope.ss[index]);
};
The directive uses $parse to convert an expression into a function that will be called from the event listener.
app.directive('clickChildren', function($parse){
return {
restrict: 'A',
link: function(scope, element, attrs){
var selector = attrs.selector;
var fun = $parse(attrs.clickChildren);
element.on('click', selector, function(e){
// no need to create a jQuery object to get the attribute
var idx = e.target.getAttribute('data-index');
fun(scope)(idx);
});
}
};
});
Plunker: http://plnkr.co/edit/yWCLvRSLCeshuw4j58JV?p=preview
Note: Functions can be delegated to directives using isolate scopes {fun: '&'}, which is worth a look, but this increases complexity.

Working off of jm-'s example here, I wrote a more concise and flexible version of this directive. Thought I'd share. Credit goes to jm- ;)
My version attempts to call the function name as $scope[ fn ]( e, data ), or fails gracefully.
It passes an optional json object from the element which was clicked. This allows you to use Angular expressions and pass numerous properties to the method being called.
HTML
<ul delegate-clicks="handleMenu" delegate-selector="a">
<li ng-repeat="link in links">
<a href="#" data-ng-json='{ "linkId": {{link.id}} }'>{{link.title}}</a>
</li>
</ul>
Javascript
Controller Method
$scope.handleMenu = function($event, data) {
$event.preventDefault();
$scope.activeLinkId = data.linkId;
console.log('handleMenu', data, $scope);
}
Directive Constructor
// The delegateClicks directive delegates click events to the selector provided in the delegate-selector attribute.
// It will try to call the function provided in the delegate-clicks attribute.
// Optionally, the target element can assign a data-ng-json attribute which represents a json object to pass into the function being called.
// Example json attribute: <li data-ng-json='{"key":"{{scopeValue}}" }'></li>
// Use case: Delegate click events within ng-repeater directives.
app.directive('delegateClicks', function(){
return function($scope, element, attrs) {
var fn = attrs.delegateClicks;
element.on('click', attrs.delegateSelector, function(e){
var data = angular.fromJson( angular.element( e.target ).data('ngJson') || undefined );
if( typeof $scope[ fn ] == "function" ) $scope[ fn ]( e, data );
});
};
});
I'd love to hear feedback if anyone wishes to contribute.
I didn't test the handleMenu method since I extracted this from a more complex application.

Starting from BradGreens' delegateClicks above, I've adapted some code from georg which allows me to place the handleMenu function deeper in $scope (e.g. $scope.tomato.handleMenu).
app.directive('delegateClicks', function () {
return function ($scope, element, attrs) {
var fn = attrs.delegateClicks.split('.').reduce(function ($scope, p) { return $scope[p] }, $scope);
element.on('click', attrs.delegateSelector, function (e) {
var data = angular.fromJson(angular.element(e.target).data('ngJson') || undefined);
if (typeof fn == "function") fn(e, data);
});
};
});

According to the issue on GitHub there is no performance advantage to delegating event handling.
Simply use the ng-click directive with the item, $index, and $event:
<ul>
<li ng-repeat="item in collection"
ng-click="lineClicked(item, $index, $event)">
{{item}}
</li>
</ul>
$scope.lineClicked = function(item, index, event) {
console.log("line clicked", item, index);
console.log(event.target)
});
For more information, see
AngularJS Developer Guide - $event
AngularJS ng-repeat Directive API Reference - Special properties

Related

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()

Angular ng-init pass element to scope

Is there a way to get the current element where my ng-init is currently binded on?
For example:
<div ng-init="doSomething($element)"></div>
I believe that there is a way for ng-click but I can't do this using ng-init like this:
<div ng-click="doSomething($event)"></div>
Controller:
$scope.doSomething = function(e){
var element = angular.element(e.srcElement);
}
How do I do this with ng-init?
Your HTML:
<div ng-app='app' ng-controller="Ctrl">
<div my-dir></div>
</div>
Your Javascript:
var app = angular.module('app', [], function () {});
app.controller('Ctrl', function ($scope) {
$scope.doSomething = function (e) {
alert(e);
};
});
app.directive('myDir', function () {
return function (scope, element, attrs) {
scope.doSomething(element);
};
});
From above, element will be your DOM object.
Don't do it.
As #CodeHater said, handling DOM manipulation in a directive is a better solution than engaging controller with the element.
I was also looking for similar thing but finally I created one more directive added to the child div element. In the directive code block I get the element object and placed all my event related function and other instructions over there. Also, I add the element to $scope object, this help me to use this object else where as well and no need to find it every time I need it.

AngularJS - Find Element with attribute

I'm new to AngularJS. I've learned that I can find elements in the DOM using queries like the following:
var e = angular.element(document.querySelector('#id'));
var e = angular.element(elem.querySelector('.classname'));
This is useful for finding elements by ID, or by CSS class name. However, I need to be able to find an element using a different approach. I have an element that looks like the following:
<div my-directive class='myContainer'>...</div>
I can't query on 'myContainer' because of how much its reused. For that reason, I would like to find any element with the attribute 'my-directive'. How do I search the DOM and find any element that makes use of 'my-directive'?
Rather than querying the DOM for elements (which isn't very angular see "Thinking in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.
So in your myDirective
return {
link: function (scope, element, attr) {
element.html('Hello world');
}
}
If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers
angular.element(document.querySelectorAll("[my-directive]"));
however you would need to use jquery to support IE8 and backwards
angular.element($("[my-directive]"));
or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?
You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)
If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.
So, for this HTML:
<div ng-controller='MyCtrl'>
<div>
<div name='foo' class='myElementClass'>this one</div>
</div>
</div>
This AngularJS code should work:
angular.module('MyClient').controller('MyCtrl', [
'$scope',
'$element',
'$log',
function ($scope, $element, $log) {
// Find the element by its class attribute, within your controller's scope
var myElements = $element.find('.myElementClass');
// myElements is now an array of jQuery DOM elements
if (myElements.length == 0) {
// Not found. Are you sure you've included the full jQuery?
} else {
// There should only be one, and it will be element 0
$log.debug(myElements[0].name); // "foo"
}
}
]);
Your use-case isn't clear. However, if you are certain that you need this to be based on the DOM, and not model-data, then this is a way for one directive to have a reference to all elements with another directive specified on them.
The way is that the child directive can require the parent directive. The parent directive can expose a method that allows direct directive to register their element with the parent directive. Through this, the parent directive can access the child element(s). So if you have a template like:
<div parent-directive>
<div child-directive></div>
<div child-directive></div>
</div>
Then the directives can be coded like:
app.directive('parentDirective', function($window) {
return {
controller: function($scope) {
var registeredElements = [];
this.registerElement = function(childElement) {
registeredElements.push(childElement);
}
}
};
});
app.directive('childDirective', function() {
return {
require: '^parentDirective',
template: '<span>Child directive</span>',
link: function link(scope, iElement, iAttrs, parentController) {
parentController.registerElement(iElement);
}
};
});
You can see this in action at http://plnkr.co/edit/7zUgNp2MV3wMyAUYxlkz?p=preview

Bind and parse HTML content

I am using AngularJS v1.2.1.
The improved ng-bind-html directive allows me to trust unsafe Html into my view.
Example
HTML:
<div ng-repeat="example in examples" ng-bind-html="example.content()"></div>
JS:
function controller($scope, $sce)
{
function ex()
{
this.click = function ()
{
alert("clicked");
}
this.content() = function ()
{
//if
return $sce.trustAsHtml('<button ng-click="click()">some text</button>');
// no problem, but click is not called
//when
return $sce.parseAsHtml('<button ng-click="click()">some text</button>');
//throw an error
}
}
$scope.examples = [new ex(), new ex()];
}
My question is, how to bind HTML content that may contain Angular expressions or directives ??
If you need dynamic templates per element, as your question suggests, one solution would be to use $compile within a directive to parse the HTML within the context of the local scope. A simple version of this is shown in this Plunk.
An example directive:
app.directive('customContent', function($compile) {
return function(scope, el, attrs) {
el.replaceWith($compile(scope.example.content)(scope));
}
});
The corresponding HTML:
<div ng-repeat="example in examples">
<div custom-content></div>
</div>
Notice that, in the Plunk controller, I've pulled out the click function into the scope for simplicity, since in the template HTML you are calling click() in the context of the scope, not on the example object. There are a couple ways you could use a different click function for each example, if that's what you'd like to do. This egghead.io screencast has a good example of passing an expression into a directive explicitly; in your case, it could be a click function or the whole example object, depending on what you need.

Creating a scope-independent fadein/fadeout directive in AngularJS

To set the stage - this is not happening within a single scope, where I can bind a simple attribute. The element I want to fade in/out does not sit inside a controller, it sits inside the ng-app (rootScope). Further, the button that's clicked is in a child scope about 3 children deep from root.
Here is how I'm currently solving this:
HTML (sitting in root scope):
<ul class="nav-secondary actions"
darthFader fadeDuration="200"
fadeEvent="darthFader:secondaryNav">
Where darthFader is my directive.
Directive:
directive('darthFader',
function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
$scope.$on(attrs.fadeevent, function(event,options) {
$(element)["fade" + options.fade || "In"](attrs.fadeduration || 200);
});
}
}
})
So here I'm creating an event handler, specific to a given element, that is calling fadeIn or fadeOut, depending on an option being passed through the event bus (or defaulting to fadeIn/200ms).
I am then broadcasting an event from $rootScope to trigger this event:
$rootScope.$broadcast('darthFader:secondaryNav', { fade: "Out"});
While this works, I'm not crazy about creating an event listener for every instance of this directive (while I don't anticipate having too many darthFader's on a screen, it's more for the pattern I would establish). I'm also not crazy about coupling my attribute in my view with an event handler in both my controller & directive, but I don't currently have a controller wrapping the secondary-nav, so I'd have to bind the secondaryNav to $rootScope, which I don't love either. So my questions:
Is there a way to do this without creating an event handler every time I instantiate my directive? (maybe a service to store a stateful list of elements?)
How should I decouple my view, controller & directive?
Any other obvious questions I'm missing?
Cheers!
You mention in your question
The element I want to fade in/out does not sit inside a controller, it sits inside the ng-app (rootScope).
I believe if I were to write this same functionality, I would put the element in its own controller--controllers are responsible for managing the intersection of the view and the model, which is exactly what you're trying to do.
myApp.controller('NavController', function($scope) {
$scope.fadedIn = false;
});
<ul ng-controller="NavController"
class="nav-secondary actions"
darthFader fadeDuration="200"
fadeShown="fadedIn">
myApp.directive('darthFader', function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
var duration = attrs.fadeDuration || 200;
$scope.$watch(attrs.fadeShown, function(value) {
if (value)
$(element).fadeIn(duration);
else
$(element).fadeOut(duration);
});
}
};
});
If you're worried about sharing the fade in/out state between multiple controllers, you should create a service to share this state. (You could also use $rootScope and event handlers, but I generally find shared services easier to debug and test.)
myApp.value('NavigationState', {
shown: false
});
myApp.controller('NavController', function($scope, NavigationState) {
$scope.nav = NavigationState;
});
myApp.controller('OtherController', function($scope, NavigationState) {
$scope.showNav = function() {
NavigationState.shown = true;
};
$scope.hideNav = function() {
NavigationState.shown = false;
};
});
<ul ng-controller="NavController"
class="nav-secondary actions"
darthFader fadeDuration="200"
fadeShown="nav.shown">
<!-- ..... -->
<div ng-controller="OtherController">
<button ng-click="showNav()">Show Nav</button>
<button ng-click="hideNav()">Hide Nav</button>
</div>
Create a custom service, inject it in the controller. Call a method on that service that will do the fade-in/fade-out etc. Pass a parameter to convey additional information.

Resources