Reduce events in dynamic menu in AngularJS? - events

I've built a dynamic menu which also have highlighting. Now i got a problem, number of path-change events are increasing along with menu elements.
Of course, that's the result of applying directive on each element of the menu.
Custom directives at the moment is my most weak place, and i don't have idea how to refactor all this.
I also made an attempt to put directive in root element of menu (ul) in order to register watch once, but stuck on accessing the deep children elements (ul->li->a.href).
Here's the directive:
app.directive("testdir", function($location)
{
return {
restrict: 'A',
link: function(scope, element, attrs, controller) {
scope.$watch(function() { return $location.path(); }, function(path)
{
scope.$parent.firedEvents++;
path=path.substring(1);
if(path === element.children().attr("href").substring(2))
{
element.addClass("activeLink");
}
else
{
element.removeClass("activeLink");
}
})
}
};
And HTML Part:
<ul ng-app="test" ng-controller="MenuCtrl">
<li ng-repeat="link in menuDef" testdir>{{link.linkName}}</li>
</ul>
Whole example on JsFiddle
How this can be refactored? I'm exhausted.
and, i'm moving in the right direction? I have a feeling that this thing could be done in bit easier way, but maybe i'm wrong.

First of all, your firedEvents means how many time the callback has been called, not how many times the location actually changed, it's not the "number of path-change events"!
You have 20 (as in your fiddle) scopes are watching the location change, when you click on a different link other than the current active one, the location changes, ALL of the 20 scopes will see the change and call their own $watch callback functions, and each call to the callback will increase your firedEvents, so the result is what you have seen: the count goes up by 20.
Therefore, if you want to make the firedEvents to count how many time location has changed, you should move scope.$parent.firedEvents++; into the if. But keep in mind that every click will still cause the callback function be called by 20 times!
There are many ways to achieve the same effect you're trying to do here, I have a solution for you without digging into directive at all. Here you go:
HTML
<ul ng-controller="MenuCtrl">
<li ng-repeat="link in menuDef" ng-class="{activeLink: link.isActive}" ng-click="onLinkClick(link)">{{link.linkName}}
</li>
</ul>
JS
app.controller("MenuCtrl", function ($scope, $location) {
var menugen = [];
for (var i = 1; i <= 20; i++) {
menugen.push({
linkName: "Link " + i,
url: "#/url" + i
});
}
$scope.menuDef = menugen;
var activeLink = null;
$scope.onLinkClick = function (link) {
if (activeLink && $scope.activeLink !== link) {
activeLink.isActive = false;
}
link.isActive = true;
activeLink = link;
};
});
jsFiddle
Update
My first attempt is targeting simplicity, but as #VirtualVoid pointed out, it has a huge drawback -- it can't easily handle location change from outside of the menu.
Here, I came up a better solution: adding a directive to the ul, watch location change in there, and update activeLink in the callback function of the watch. In this way, one $watch is called, and only one callback will be called for a click.
JS
app.directive('menu', function ($location) {
return {
restrict: 'A',
controller: function ($scope, $location) {
var links = [];
this.registerLink = function (elem, path) {
links.push({
elem: elem,
path: path
});
};
$scope.$watch(function () {
return $location.path();
}, function (path) {
for (var i = 0; i < links.length; i++) {
if (path === links[i].path) {
links[i].elem.addClass('activeLink');
} else {
links[i].elem.removeClass('activeLink');
}
}
});
}
};
}).
directive("testdir", function () {
return {
restrict: 'A',
require: '^menu',
link: function (scope, element, attrs, controller) {
controller.registerLink(element, scope.link.url.substring(1));
}
};
});
HTML
<ul ng-app="test" ng-controller="MenuCtrl" menu>
<li ng-repeat="link in menuDef" testdir>
{{link.linkName}}
</li>
</ul>
jsFiddle: http://jsfiddle.net/jaux/MFYCX/

Related

Getting the count of elements in a list from Nightwatch

I have the following DOM structure:
<div data-qa-id="criteriaDisplay">
<ul>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
</div>
I would like to write a command that returns the number of items in the list above. I am a newbie to Nightwatch. Here's my attempt to do this. My thinking is to start with the <ul> under the criteriaDisplay element and then count the <li> items under it. So I am trying to use the elementIdElements api, but it is not working:
var criteriaDisplayCommands = {
getNumberOfItems: function(callback) {
var self = this;
console.log(this);
return this.api.elementIdElements('#myList', 'css selector', 'li', function(result) {
callback.call(self, result);
});
}
};
module.exports = {
url: function() {
return this.api.launchUrl + '/search';
},
sections: {
criteriaDisplay: {
selector: '[data-qa-id="criteriaDisplay"]',
commands: [criteriaDisplayCommands],
elements: {
myList: 'ul'
}
}
}
};
Can someone please help me with the right way to do this?
I dont think this is right:
return this.api.elementIdElements('#myList', 'css selector', 'li', function(result) {
callback.call(self, result);
});
Since elementIdElements requires the first parameter to be an elementId. In your case its a css selector.
The second i'm not sure about is that you are using custom selectors in the selenium api. I dont think that this is gonna work (but i'm not sure about this)
From the doc's section about defining-elements:
Using the elements property allows you to refer to the element by its name with an "#" prefix, rather than selector, when calling element commands and assertions (click, etc).
Since you are using the selenium api and not a command or assertion, i dont think that it would be a valid input.
You could use elements for getting your result, or an combination of element and elementIdElements.
The simple one is only using elements as shown below:
this.api.elements('css selector', 'ul li', function (result) {
console.log(result.value.length) //(if there are 3 li, here should be a count of 3)
callback.call(self, result);
});`

How to show a spinner in Meteor for the duration of an event

In a Meteor app, one function that runs on a click takes a while to run on some slower devices. As a result, on these slow devices, the app doesn't seem to do anything until after the function has completed.
The function in question loops through a largish array. It does not do any external stuff, or method calls.
To visually clue in the user, I want to show a spinner to the user (on slow devices). Ideally, I would show the spinner at the start of the event, and then remove the spinner at the end of the event. However, if my understanding of Meteor is correct (and based on what seems to be happening when I try it out), all template updates specified during the event are only propagated at the end of the event. So, as a result, the spinner never shows.
How can I make this work as intended?
Current setup (edit with actual code):
In categories.html:
{{#if hasSubCategories}}
<a href='#_' id='categorySelect-{{id}}' class='btn categorySelect pull-right
{{#if allSubsSelected}}
btn-danger
{{else}}
btn-success
{{/if}}
'>{{#if isFlipping}}<span id='spinner-{{id}}'>flip</span>{{/if}}<span class="glyphicon
{{#if allSubsSelected}}
glyphicon-remove
{{else}}
glyphicon-ok
{{/if}}
" aria-hidden="true"></span></a>
{{/if}}
In categories.js:
Template.categories.events({
"click .categorySelect": function (event) {
Session.set('categorySpinner', this.id);
categoryFlipper(this.id, function() {
Session.set('categorySpinner', "");
});
return false;
},
});
Template.categories.helpers({
allSubsSelected: function() {
var finder = Categories.find({parentId: this.id});
var allSelected = true;
finder.forEach(function(item) {
if (!($.inArray(item.id, Session.get("categoriesSelected")) !== -1)) {
allSelected = false;
}
});
return allSelected;
},
isFlipping: function() {
if (Session.get("categorySpinner") == this.id)
return true;
else
return false;
}
});
In main.js:
categoryFlipper = function (id, callback) {
var finder = Categories.find({parentId: id});
var allSelected = true;
finder.forEach(function(item) {
if (!($.inArray(item.id, Session.get("categoriesSelected")) !== -1)) {
allSelected = false;
}
});
var t = Session.get("categoriesSelected");
if (allSelected) {
finder.forEach(function(item) {
t.splice($.inArray(item.id, t), 1);
});
}
else {
finder.forEach(function(item) {
if (!($.inArray(item.id, t) !== -1)) {
t.push(item.id);
}
});
}
Session.set("categoriesSelected", t);
callback();
}
Looking at your sample code (though I still don't have a complete picture since I don't see the helper definitions for allSubsSelected and isFlipping), I'm pretty sure that your categoryFlipper function executes so quickly that you never really see the spinner. There's nothing in that code that would really take any significant amount of time. You have a find() call, but that's not what really takes the most amount of time. It's your subscribe() call that you usually need to figure in some delay for as the data is pulled from the database to the mini-mongo client in the browser.
Something like this is fairly common:
{{#unless Template.subscriptionsReady}}
spinner here...
{{else}}
Content here.
{{/unless}}
That way, while your subscription is triggering the publication and pulling data down, Template.subscriptionsReady returns false, and the spinner is shown. Try that approach instead.

Holding down mouse button on SlickGrid header to get column information

I'm trying to make a special menu pop up in Slick Grid when the user holds down the mouse button for some amount of time. The menu has to relate specifically to that column, so I need to somehow retrieve the information from that column. Since the popup will appear during the time the mouse button is held, I can't use an onclick event.
I do have some code I used to make this work for the main body of the grid:
// Attach the mousedown and mouseup functions to the entire grid
$(document).ready(function () {
$("#myGrid").bind("mousedown", function (e, args) {
var event = e;
timer = setTimeout(function () { heldMouse(event, args); }, 500);
})
.bind("mouseup", function () {
clearTimeout(timer);
});
});
function heldMouse(e, args) {
// if header click -
// showHeaderContextMenu(e, args)
// else
showContextMenu(e);
mouseHeldDown = false;
}
// Displays context menu
function showContextMenu(e) {
var cell = grid.getCellFromEvent(e);
grid.setActiveCell(cell.row, cell.cell);
$("#slickGridContextMenu")
.css("top", e.pageY - 5)
.css("left", e.pageX - 5)
.show();
}
(I know args is going to be empty, it's there more as a placeholder than anything else for now)
This works perfectly fine for holding down on the main body, but if I do this on the header, since I no longer have access to getCellFromEvent and the mouse events I've called can't get args from anywhere, I'm unsure how I can get information about the header and which column I'm in. Is there a bit of functionality in Slickgrid that I've overlooked? I didn't notice a mousedown event I could subscribe to.
I had a thought that I could bind separate events to both the header and the body, but I'm not sure if that would still be able to get me the information I need. Looking at the tags, I see two possibilities: slick-header-column, which has an id (slickgrid_192969DealNbr) but I'm not sure how to reliably remove that number (where does it come from?), or slick-column-name, where I can get the html from that tag, but sometimes those names are altered and I'd rather not deal with that unless I absolutely have to. This is what I'm referring to:
<DIV id=slickgrid_192969OrdStartDate_ATG title="" class="ui-state-default slick-header-column" style="WIDTH: 74px">
<SPAN class=slick-column-name>
<SPAN style="COLOR: green">OrdStartDate</SPAN></SPAN><SPAN class=slick-sort-indicator></SPAN>
<DIV class=slick-resizable-handle></DIV></DIV>
Also, I have this:
grid.onHeaderContextMenu.subscribe(function (e, args) {
e.preventDefault();
// args.column - the column information
showHeaderContextMenu(e, args);
});
Is there a way perhaps I could trigger this event from the mouse holding methods and receive args with the column name in it? This was just a thought, I'm not really sure how the triggering works with SlickGrid/JQuery, but figured it might be possible.
Thanks for any suggestions!
Try something like this instead (demo):
$(function () {
var timer;
$("#myGrid")
.bind("mousedown", function (e, args) {
var event = e; // save event object
timer = setTimeout(function(){
doSomething(event, args);
}, 1000);
})
.bind("mouseup mousemove", function () {
clearTimeout(timer);
});
});
function doSomething(e, args){
alert('YAY!');
};
And in case you were wondering why I saved the e (event object), it is because of this (ref):
The event object is valid only for the duration of the event. After it returns you can't expect it to remain unchanged. In fact, the entire native event object (event.originalEvent) cannot be read in IE6/7/8 after the event has passed--it's gone and will throw an error if you try to access it. If you need an unchanging copy of some event data, make one.
I got something that works, for now, with the help of Mottie's idea (was not aware of "closest" in jquery). It's not elegant, but so be it.
Here's the structure of one of the column tags:
<DIV id=slickgrid_132593DealNbr title="" class="ui-state-default slick-header-column slick-header-column-sorted" style="WIDTH: 49px">
<SPAN class=slick-column-name>DealNbr</SPAN>
<SPAN class="slick-sort-indicator slick-sort-indicator-asc"></SPAN>
<DIV class=slick-resizable-handle></DIV></DIV>
And here are the calls made to get it.
$(document).ready(function () {
$("#myGrid").bind("mousedown", function (e) {
var event = e;
timer = setTimeout(function () { heldMouse(event); }, 500);
})
.bind("mouseup", function () {
clearTimeout(timer);
$("body").one("click", function () { cleanup(); });
});
});
function heldMouse(e) {
// If the click was not on one of the headers, it won't find this
if ($(e.target).closest('.slick-header-column').html() != null) {
var $foundColumnHeader = $(e.target).closest('.slick-header-column');
// columns being used to populate SlickGrid's columns
var held_col = columns[$foundColumnHeader.index()];
showHeaderContextMenu(e, { column: held_col });
}
else {
showContextMenu(e);
}
mouseHeldDown = false;
}
Thanks!

Prototype.js event observe click intercept and stop propagation

I have a page that is built around a wrapper with some very defined logic. There is a Save button on the bottom of the wrapped form that looks like this:
<form>
... my page goes here...
<input id="submitBtnSaveId" type="button" onclick="submitPage('save', 'auto', event)" value="Save">
</form>
This cannot change...
Now, I'm writing some javascript into the page that gets loaded in "...my page goes here...". The code loads great and runs as expected. It does some work around the form elements and I've even injected some on-page validation. This is where I'm stuck. I'm trying to "intercept" the onclick and stop the page from calling "submitPage()" if the validation fails. I'm using prototype.js, so I've tried all variations and combinations like this:
document.observe("dom:loaded", function() {
Element.observe('submitBtnSaveId', 'click', function (e) {
console.log('Noticed a submit taking place... please make it stop!');
//validateForm(e);
Event.stop(e);
e.stopPropagation();
e.cancelBubble = true;
console.log(e);
alert('Stop the default submit!');
return false;
}, false);
});
Nothing stops the "submitPage()" from being called! The observe actually works and triggers the console message and shows the alert for a second. Then the "submitPage()" kicks in and everything goes bye-bye. I've removed the onclick attached to the button in Firebug, and my validation and alert all work as intended, so it leads me to think that the propagation isn't really being stopped for the onclick?
What am I missing?
So based on the fact that you can't change the HTML - here's an idea.
leave your current javascript as is to catch the click event - but add this to the dom:loaded event
$('submitBtnSaveId').writeAttribute('onclick',null);
this will remove the onclick attribute so hopefully the event wont be called
so your javascript will look like this
document.observe("dom:loaded", function() {
$('submitBtnSaveId').writeAttribute('onclick',null);
Element.observe('submitBtnSaveId', 'click', function (e) {
console.log('Noticed a submit taking place... please make it stop!');
//validateForm(e);
Event.stop(e);
e.stopPropagation();
e.cancelBubble = true;
console.log(e);
alert('Stop the default submit!');
return false;
submitPage('save', 'auto', e);
//run submitPage() if all is good
}, false);
});
I took the idea presented by Geek Num 88 and extended it to fully meet my need. I didn't know about the ability to overwrite the attribute, which was great! The problem continued to be that I needed to run submitPage() if all is good, and that method's parameters and call could be different per page. That ended up being trickier than just a simple call on success. Here's my final code:
document.observe("dom:loaded", function() {
var allButtons = $$('input[type=button]');
allButtons.each(function (oneButton) {
if (oneButton.value === 'Save') {
var originalSubmit = oneButton.readAttribute('onclick');
var originalMethod = getMethodName(originalSubmit);
var originalParameters = getMethodParameters(originalSubmit);
oneButton.writeAttribute('onclick', null);
Element.observe(oneButton, 'click', function (e) {
if (validateForm(e)) {
return window[originalMethod].apply(this, originalParameters || []);
}
}, false);
}
});
});
function getMethodName(theMethod) {
return theMethod.substring(0, theMethod.indexOf('('))
}
function getMethodParameters(theMethod) {
var parameterCommaDelimited = theMethod.substring(theMethod.indexOf('(') + 1, theMethod.indexOf(')'));
var parameterArray = parameterCommaDelimited.split(",");
var finalParamArray = [];
parameterArray.forEach(function(oneParam) {
finalParamArray.push(oneParam.trim().replace("'","", 'g'));
});
return finalParamArray;
}

Calling a function when ng-repeat has finished

What I am trying to implement is basically a "on ng repeat finished rendering" handler. I am able to detect when it is done but I can't figure out how to trigger a function from it.
Check the fiddle:http://jsfiddle.net/paulocoelho/BsMqq/3/
JS
var module = angular.module('testApp', [])
.directive('onFinishRender', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
element.ready(function () {
console.log("calling:"+attr.onFinishRender);
// CALL TEST HERE!
});
}
}
}
});
function myC($scope) {
$scope.ta = [1, 2, 3, 4, 5, 6];
function test() {
console.log("test executed");
}
}
HTML
<div ng-app="testApp" ng-controller="myC">
<p ng-repeat="t in ta" on-finish-render="test()">{{t}}</p>
</div>
Answer:
Working fiddle from finishingmove: http://jsfiddle.net/paulocoelho/BsMqq/4/
var module = angular.module('testApp', [])
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit(attr.onFinishRender);
});
}
}
}
});
Notice that I didn't use .ready() but rather wrapped it in a $timeout. $timeout makes sure it's executed when the ng-repeated elements have REALLY finished rendering (because the $timeout will execute at the end of the current digest cycle -- and it will also call $apply internally, unlike setTimeout). So after the ng-repeat has finished, we use $emit to emit an event to outer scopes (sibling and parent scopes).
And then in your controller, you can catch it with $on:
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
//you also get the actual event object
//do stuff, execute functions -- whatever...
});
With html that looks something like this:
<div ng-repeat="item in items" on-finish-render="ngRepeatFinished">
<div>{{item.name}}}<div>
</div>
Use $evalAsync if you want your callback (i.e., test()) to be executed after the DOM is constructed, but before the browser renders. This will prevent flicker -- ref.
if (scope.$last) {
scope.$evalAsync(attr.onFinishRender);
}
Fiddle.
If you really want to call your callback after rendering, use $timeout:
if (scope.$last) {
$timeout(function() {
scope.$eval(attr.onFinishRender);
});
}
I prefer $eval instead of an event. With an event, we need to know the name of the event and add code to our controller for that event. With $eval, there is less coupling between the controller and the directive.
The answers that have been given so far will only work the first time that the ng-repeat gets rendered, but if you have a dynamic ng-repeat, meaning that you are going to be adding/deleting/filtering items, and you need to be notified every time that the ng-repeat gets rendered, those solutions won't work for you.
So, if you need to be notified EVERY TIME that the ng-repeat gets re-rendered and not just the first time, I've found a way to do that, it's quite 'hacky', but it will work fine if you know what you are doing. Use this $filter in your ng-repeat before you use any other $filter:
.filter('ngRepeatFinish', function($timeout){
return function(data){
var me = this;
var flagProperty = '__finishedRendering__';
if(!data[flagProperty]){
Object.defineProperty(
data,
flagProperty,
{enumerable:false, configurable:true, writable: false, value:{}});
$timeout(function(){
delete data[flagProperty];
me.$emit('ngRepeatFinished');
},0,false);
}
return data;
};
})
This will $emit an event called ngRepeatFinished every time that the ng-repeat gets rendered.
How to use it:
<li ng-repeat="item in (items|ngRepeatFinish) | filter:{name:namedFiltered}" >
The ngRepeatFinish filter needs to be applied directly to an Array or an Object defined in your $scope, you can apply other filters after.
How NOT to use it:
<li ng-repeat="item in (items | filter:{name:namedFiltered}) | ngRepeatFinish" >
Do not apply other filters first and then apply the ngRepeatFinish filter.
When should I use this?
If you want to apply certain css styles into the DOM after the list has finished rendering, because you need to have into account the new dimensions of the DOM elements that have been re-rendered by the ng-repeat. (BTW: those kind of operations should be done inside a directive)
What NOT TO DO in the function that handles the ngRepeatFinished event:
Do not perform a $scope.$apply in that function or you will put Angular in an endless loop that Angular won't be able to detect.
Do not use it for making changes in the $scope properties, because those changes won't be reflected in your view until the next $digest loop, and since you can't perform an $scope.$apply they won't be of any use.
"But filters are not meant to be used like that!!"
No, they are not, this is a hack, if you don't like it don't use it. If you know a better way to accomplish the same thing please let me know it.
Summarizing
This is a hack, and using it in the wrong way is dangerous, use it only for applying styles after the ng-repeat has finished rendering and you shouldn't have any issues.
If you need to call different functions for different ng-repeats on the same controller you can try something like this:
The directive:
var module = angular.module('testApp', [])
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit(attr.broadcasteventname ? attr.broadcasteventname : 'ngRepeatFinished');
});
}
}
}
});
In your controller, catch events with $on:
$scope.$on('ngRepeatBroadcast1', function(ngRepeatFinishedEvent) {
// Do something
});
$scope.$on('ngRepeatBroadcast2', function(ngRepeatFinishedEvent) {
// Do something
});
In your template with multiple ng-repeat
<div ng-repeat="item in collection1" on-finish-render broadcasteventname="ngRepeatBroadcast1">
<div>{{item.name}}}<div>
</div>
<div ng-repeat="item in collection2" on-finish-render broadcasteventname="ngRepeatBroadcast2">
<div>{{item.name}}}<div>
</div>
The other solutions will work fine on initial page load, but calling $timeout from the controller is the only way to ensure that your function is called when the model changes. Here is a working fiddle that uses $timeout. For your example it would be:
.controller('myC', function ($scope, $timeout) {
$scope.$watch("ta", function (newValue, oldValue) {
$timeout(function () {
test();
});
});
ngRepeat will only evaluate a directive when the row content is new, so if you remove items from your list, onFinishRender will not fire. For example, try entering filter values in these fiddles emit.
If you’re not averse to using double-dollar scope props and you’re writing a directive whose only content is a repeat, there is a pretty simple solution (assuming you only care about the initial render). In the link function:
const dereg = scope.$watch('$$childTail.$last', last => {
if (last) {
dereg();
// do yr stuff -- you may still need a $timeout here
}
});
This is useful for cases where you have a directive that needs to do DOM manip based on the widths or heights of the members of a rendered list (which I think is the most likely reason one would ask this question), but it’s not as generic as the other solutions that have been proposed.
I'm very surprised not to see the most simple solution among the answers to this question.
What you want to do is add an ngInit directive on your repeated element (the element with the ngRepeat directive) checking for $last (a special variable set in scope by ngRepeat which indicates that the repeated element is the last in the list). If $last is true, we're rendering the last element and we can call the function we want.
ng-init="$last && test()"
The complete code for your HTML markup would be:
<div ng-app="testApp" ng-controller="myC">
<p ng-repeat="t in ta" ng-init="$last && test()">{{t}}</p>
</div>
You don't need any extra JS code in your app besides the scope function you want to call (in this case, test) since ngInit is provided by Angular.js. Just make sure to have your test function in the scope so that it can be accessed from the template:
$scope.test = function test() {
console.log("test executed");
}
A solution for this problem with a filtered ngRepeat could have been with Mutation events, but they are deprecated (without immediate replacement).
Then I thought of another easy one:
app.directive('filtered',function($timeout) {
return {
restrict: 'A',link: function (scope,element,attr) {
var elm = element[0]
,nodePrototype = Node.prototype
,timeout
,slice = Array.prototype.slice
;
elm.insertBefore = alt.bind(null,nodePrototype.insertBefore);
elm.removeChild = alt.bind(null,nodePrototype.removeChild);
function alt(fn){
fn.apply(elm,slice.call(arguments,1));
timeout&&$timeout.cancel(timeout);
timeout = $timeout(altDone);
}
function altDone(){
timeout = null;
console.log('Filtered! ...fire an event or something');
}
}
};
});
This hooks into the Node.prototype methods of the parent element with a one-tick $timeout to watch for successive modifications.
It works mostly correct but I did get some cases where the altDone would be called twice.
Again... add this directive to the parent of the ngRepeat.
Very easy, this is how I did it.
.directive('blockOnRender', function ($blockUI) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (scope.$first) {
$blockUI.blockElement($(element).parent());
}
if (scope.$last) {
$blockUI.unblockElement($(element).parent());
}
}
};
})
Please have a look at the fiddle, http://jsfiddle.net/yNXS2/. Since the directive you created didn't created a new scope i continued in the way.
$scope.test = function(){... made that happen.

Resources