How to create on-change directive for AngularJS? - events

Normally ng-model updates bound model each time user pushes the key:
<input type="text" ng-model="entity.value" />
This works great in almost every case.
But I need it to update when onchange event occurs instead when onkeyup/onkeydown event.
In older versions of angular there was a ng-model-instant directive which worked same as ng-model works now (at least for the user - i don't know anything about their implementations).
So in older version if I just gave ng-model it was updating the model onchange and when I specified ng-model-instant it was updating the model onkeypup.
Now I need ng-model to use on "change" event of the element. I don't want it to be instant. What's the simplest way of doing this?
EDIT
The input still has to reflect any other changes to the model - if the model will be updated in other place, value of the input should reflect this change.
What I need is to have ng-model directive to work just like it worked in the older versions of angularjs.
Here is an explanation of what I'm trying to do:
http://jsfiddle.net/selbh/EPNRd/

Here I created onChange directive for you. Demo: http://jsfiddle.net/sunnycpp/TZnj2/52/
app.directive('onChange', function() {
return {
restrict: 'A',
scope:{'onChange':'=' },
link: function(scope, elm, attrs) {
scope.$watch('onChange', function(nVal) { elm.val(nVal); });
elm.bind('blur', function() {
var currentValue = elm.val();
if( scope.onChange !== currentValue ) {
scope.$apply(function() {
scope.onChange = currentValue;
});
}
});
}
};
});

See also: the AngularJS ngChange directive.
When applied to an <input> the changes occurs after each key press not on the blur event.
http://docs.angularjs.org/api/ng.directive:ngChange

Angularjs: input[text] ngChange fires while the value is changing : This answer provides a much better solution that allows the custom directive to work with ngModel so you can still use all of the other directives that go along with ngModel.
Also, an even more flexible solution that allows for specifying the event to use (not just blur) and other properties should be built in to angular very soon: https://github.com/angular/angular.js/pull/2129

I'm not sure if there is a better way to do this, but you can achieve this using a custom directive (on any jquery event you want)
<input type="text" ng-model="foo" custom-event="bar" />
<p> {{ bar }} </p>
// create the custom directive
app.directive('customEvent', function() {
return function(scope, element, attrs) {
var dest = attrs.customEvent;
$(element[0]).on('any-jquery-event', function(e) {
e.preventDefault();
// on the event, copy the contents of model
// to the destination variable
scope[dest] = scope.foo;
if (!scope.$$phase)
scope.$apply();
});
}
});

Related

Vuejs and Kendo integration

i have a problem with vuejs and kendo ui.
I need to click a tr columns
<kendo-grid-column #click="clicked"></kendo-grid-column>
i also used a #click.native but nothing
i've created also a template with <a> tag that calls "clicked" method
demo
http://dojo.telerik.com/#aldoZumaran/UTOGo
Maybe this is not exactly what you want, but it's possible to enable Sorting on the Grid and intercept the Sort Event for further handling.
Change your kendo-grid, add:
:sortable='true'
#sort='callback'
The Callback method syntax was also a bit weird, use:
callback: function(e) {
console.log(e.sort.field);
console.log(e.sort.dir);
}
Maybe this is the right place to execute your actions.
UPDATE
It's possible to call e.preventDefault(); in callback method to prevent default sorting action:
callback: function(e) {
if (e.sort.field === 'UnitPrice') {
console.log('Sort by Price not allowed!');
e.preventDefault();
}
}

Angular-Kendo window custom actions

I'm trying to create a window with a custom action using Angular-Kendo, and have reached a problem.
When using Kendo (minus angular) i would add functionality like explained here:
window.data("kendoWindow").wrapper.find(".k-i-custom").click(function(e){
alert("Custom action button clicked");
e.preventDefault();
});
However, in Angular-Kendo, access to the window object is by $scope.windowname and is only available after the kendo-window="windowname" directive.
I am currently bypassing this by binding the actions at the k-on-open like...
var firstLoad = true;
this.onOpenCallback = function () {
if (firstLoad) {
$scope.messageBodyWindow.wrapper.find(".k-i-custom").click(function (e) {
alert("OMG");
});
firstLoad = false;
}
This solution, however, feels like a cheap hack. is there a "proper" way to achieve this?
You could wrap the Angular-Kendo directive in a custom directive and put the desired functionality into the link function. This will register your custom binding once without any of this 'first time opening the window boolean' hackery.
<div custom-kendo-window>
</div>
The custom directive contains the kendo directive in its template...
.directive('customKendoWindow', function(){
return {
template: '<div kendo-window="win" k-title="\'Window\'" k-width="600" k-height="200" k-visible="false"> <div id="customAction" style="cursor: pointer;">custom click action</div></div>',
link: function(scope, element, attrs){
$('#customAction').bind('click', function(){
alert('Custom action fired!');
})
}
}
})
Here is a code pen showing the simple wrapper as shown above and then a configurable wrapper with the click binding being set up in the link functions of each of the directives.

Jquery Date-picker is not working with angular directive ng-model in Firefox

I am using simple HTML5 date control which is bound with ng-model directive, here is my code;
<input type="date" datepicker id="NextServiceDate" name="NextServiceDate" ng-model="product.NextServiceDate" />
I have noticed one thing, if I am not binding date control with ng-model then jquery date-picker works fine, but after binding with ng-model it sets date for the first time but when I am trying to update date, then it's not calling the date-picker.
Please let me know how to achieve this functionality in Firefox.
I have also created a directive for it, but it also doesn't get called when my input type is 'Date'. It works fine with input type 'text'.
One23SRCApp.directive('datepicker', function () {
return {
require: 'ngModel',
link: function (scope, el, attr, ngModel) {
$(el).datepicker({
onSelect: function (dateText) {
scope.$apply(function () {
var expression = attr.ngModel + " = " + "'" + dateText + "'";
scope.$apply(expression);
});
}
});
}
};
});
You don't need to do:
$(el).datepicker(...);
You directly get the DOM element in the directive link function (the parameter 'el' in your code).
I am not sure what are you doing here:
var value = "";
The fact that it gets called only once and not after further updates, is mostly because angular triggers all the watchers(ie. calls $digest()) when the page first loads.

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.

jQuery Delegate not binding like I want it to

Using jQuery 1.7
I'm having trouble binding a Click event to some dynamically loaded content.
I've looked around, tried .live, .delegate and .on, and I just can't get it to work.
This is my code:
$(".fileexplorer_folderdlg").delegate(".delete", "click", function () {
console.log("Hello world!");
});
The thing is, .fileexplorer_folderdlg is dynamically loaded. If I use .fileexplorer (not dynamically loaded), it works, but I have more elements with the .delete class that I do not wish to bind to (and neither element classes can be renamed or changed for various reasons).
I also tried using .fileexplorer_folderdlg .delete as the .delegate selector, didnt work either!
Of course I could just add another unique class to the elements I wish to bind to, but this really should work, right?
I believe this would work:
$(document).on('click', '.delete', function() {
if ($(this).closest('.fileexplorer_folderdlg').length) {
console.log('hello, world!');
}
});
or even just:
$(document).on('click', '.fileexplorer_folderdlg .delete', function() {
console.log('hello, world!');
});
As you've found, you can't bind on .fileexplorer_folderdlg because it's dynamic. You therefore need to bind on some static element that will contain that element at some point in the future.
Instead, this binds on the document (but will unfortunately fire for every single click on the document thereafter).
EDIT by Jeff
Although the code above did not work, modifying it a bit did the job, although not the most desirable solution.
$(document).on('click', '.delete', function () {
if($(this).closest(".fileexplorer") != null)
console.log("Thanks for your help!");
});
It works, but this event is fired for all other .delete classes, of which there are many. What I do not understand though, is why using .fileexplorer_folderdlg .delete did not work!

Resources