what is the best way to use jQuery plugin into Angular js - javascript

I am using a jQuery plugin with Angular project but with the jQuery way like
$(document).ready(function(){
//calling plugin here
});
This is working fine. I know this is not the right way to do it and it's not highly recommended, but I have already searched a couple of blogs and websites on this topic. They said that we can create directive for this but I am not able to understand how I can create any directive for a jQuery plugin and how it will work? Is it possible to create an Angular directive for each jQuery plugin?

You can create something like this
App.directive('jqueryPlugInDirective', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).[jqueryPlugin](ConfigOptions);
}
};
});
And your html will be something like
<script type="text/javascript" src="pluginLibFile.js"></script>
<div jquery-plug-in-directive></div>

It's not recomended to mix up jQuery and AngularJs but, Incase you just have to, You need to work with Angular's jqLite,
Here's the link for some reference - https://docs.angularjs.org/api/ng/function/angular.element

Well I prefer to use anonymous function passing passing global jQuery element.
(function($){
//code
})(jQuery);
Using anonymous function and passing jQuery as parameter eliminates the issues arising due to overriding of $ by some other library.
As we are passing (JQuery) global object as parameter and receiving it into ($) so, $ is now with jQuery no matter if its overridden..
However, you can go with native Angular jQuery version .. jQLite also.. using angular.Element().
You can read more about differences .. jQuery document.ready vs self calling anonymous function

Related

how to call a custom jquery function without attaching it to something

new to writing a function in jquery, just testing the waters.
I have this just to to demo:
(function ( $ ) {
$.fn.update_notifications = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
user_id: 0,
}, options );
alert('test');
};
}( jQuery ));
Which I include in a JS file included before the tag. What I want to know, is how to actually call it inside my html?
I was thinking something like:
<script type="text/javascript">
jQuery.update_notifications({
user_id: 1
});
</script>
But that tells me "jQuery.update_notifications is not a function"
You want to call it on selected element like this:
$("some_element").update_notifications();
You can find more here at the official documentation.
No, the function is not part of the jquery object, but of its fn child object
$.fn.update_notifications();
However, it doesnt make sense to add something to the jquery prototype if youre not doing sth jqueryobjectbased
To fix the issue you simply need to change $.fn.update_notifications to $.update_notifications. The $.fn namespace is used for attaching functions to instances of jQuery objects.
(function($) {
$.update_notifications = function(options) {
var settings = $.extend({
user_id: 0,
}, options);
console.log('test');
};
}(jQuery));
jQuery.update_notifications({
user_id: 1
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That being said, your example is a little redundant as you've just wrapped the existing $.extend() function without adding any real logic - although I assume this is a work in progress.
If your function has nothing to do with any DOM elements, i would suggest you not to pollute jQuery. You can very well declare this function some where else (page, separate JS file etc.).
But if you still want to do this, you can try these
$.update_notifications();
or
$(window).update_notifications();
or
$(document).update_notifications();
Why are you exactly extending the Jquery object?
Usually, lacking a valid reason to do so you would simply write a function inside your script.
Let's assume you have a valid reason and proceed:
Once you bind your function to $ or better create object like $.custom and bind the function (and rest of custom things you wanna bind to Jquery) you can use it like a normal function - only prefix it with $.custom
Not sure I understand your question but are you searching how to run that function from HTML other than using jquery?
Are you asking for an example like this?
<p id="onThis" onclick="$.custom.yourFunctionName()">Click me.</p>
That is obtrusive JS code and is not best practice when dealing with Jquery.
You wanna bind that function to element with on or click handler when document is ready:
$(document).ready( function() {
$('#onThis').on('click', function here);
// OR //
$('#onThis').click(function here);
});
If there is no reason to bind it to jQuery, don't do it you are only implying to someone reading your code something that doesn't exist ;)

When should $scope.apply() be used in angular? [duplicate]

This question already has answers here:
How do I use $scope.$watch and $scope.$apply in AngularJS?
(6 answers)
Closed 7 years ago.
What does $scope.apply do? In some cases, if $scope.apply() is not present, $scope.watch() is not triggered. For example,
The controller has the following:
setTimeout(function(){
$scope.person = someperson;
}, 500);
person is being watched in the directive.
$scope.watch('person', function(){
console.log($scope.person);
$scope.apply();
});
In this case, watch is triggered only when apply is there.
$scope.apply() will trigger the $digest loop of AngularJS. To put is simple, it's just a convenient way to trigger the app rerender.
Usually it is used when you want to run a piece of code that is outside of angular app.
Direct from the documentation:
$apply() is used to execute an expression in angular from outside of
the angular framework. (For example from browser DOM events,
setTimeout, XHR or third party libraries). Because we are calling into
the angular framework we need to perform proper scope life cycle of
exception handling, executing watches.
Example of using scope.$apply() with jQuery Datepicker:
angular.module('customApp', []).directive('datepicker', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
jQuery(element).datepicker({
onSelect: function (date) {
scope.myDate = date;
scope.$apply();
}
});
}
};
});
If you modify an AngularJS model outside (from external JavaScript) - you should use $scope.$apply() to let AngularJS know that model has changed. In your example you use setTimeout() which is an async external js method. However if you use the AngularJS $timeout you wont need to call $scope.$apply().
setTimeout(function(){}:-It is javascript function which is out of the scope of anuglar js you need to manually apply the digest cycle with the help of $scope.apply();
But instead you can use $timeout service which is more angular way.

Pass Jquery alias into javascript function

Im creating a theme for wordpress and I need to use some jQuery. Ive found bits of code online and ive made a few bits myself. However, when using jQuery provided by wordpress it is in noConflict mode and instead of using $ it is set to "jQuery". That is fine but I dont want to have to modify all my code and any code I find online to use "jQuery" instead of $.
So it tells me that by placeing function ($) at the end you are able to use the $ as the jQuery alias, but only in that functions scope. That is fine, but I was hoping that it would work and pass through to the functions I call from inside that scope. That is where my problem is. How can I make the jQuery code that uses $ inside my "resizeandcenter" function work.
jQuery('.artworklist > li > a > img').load(function ($){
resizeitems('artworklist');
});
This is my function that I want to be able to use the $ inside as I dont want to have to modify all my code / and any code I find online.
function resizeitems(elementname){
//Do some jquery stuff using $
}
Perhaps there is an alternative way to do what I am doing or I am doing it wrong?
EDIT:
My function "resizeitems" is on its own in a js file thats included in my page header.
The other code, the jQuery code in my first code block is at the bottom of the page in a script block.
So im a bit unsure about the answer saying to wrap my function?
You can wrap your entire code in a self executing closure (or an on ready/load closure) like this
(function ($) {
// do your stuff here
}(jQuery));
Then you can use $ within that closure
Here is an example on jsfiddle for you
window.addEventListener("load", function () {
(function ($jq) {
$jq("body").append($jq("<div>").text("hello"));
}(jQuery));
}, false);
Here is an example using jquery's ready event listener
jQuery(document).ready(function() {
(function ($jq) {
$jq("body").append($jq("<div>").text("hello"));
}(jQuery));
});
On jsfiddle
Or a further alternative in jquery, mostly syntax change, as suggested by #Mathletics
jQuery(function($jq) {
$jq("body").append($jq("<div>").text("hello"));
});
On jsfiddle
You need to pass jQuery into the top-level closure containing your code. Usually this is inside the $(document).ready() call. A basic example looks like this:
jQuery(function($) {
function resizeitems(elementname){
//Do some jquery stuff using $
}
$('.artworklist > li > a > img').load(function (){
resizeitems('artworklist');
});
});
jQuery is now aliased to $ inside of that closure.
All what matter is scope here. If your other functions are in some other scope you can just remap global jQuery to $ in that scope, so that you don't have to change the code.
var $ = jQuery;
You can even set it in global scope, but you may affect other usage of $ on the page if it was used for something else:
window.$ = jQuery;

extending jquery with a generic function

I am writing the a generic function for my website using jquery which would be used over the entire site for displaying a success/error message. I decided to make it a plugin.
A simple form of the plugin is given below:
; (function ($) {
jQuery.FlashMessage=function(msg){
alert(msg);
}
})(jQuery);
I wanted to know whether it is a good practice to define plugins in the jquery namespace or should it defined under $.fn.XXXX ..or am i overthinking and it doesn't matter it at all.
You add those functions to jQuery.fn which should be run on selected elements, e.g. $('div').yourFunction().
If you want a "generic" function, like $.ajax(), then you should add it to the jQuery object, like you already do. But I would use $ inside the function:
(function ($) {
$.FlashMessage=function(msg){
alert(msg);
}
})(jQuery);
So it depends on what kind of functionality you want.
jQuery.fn is equivalent to jQuery.prototype
with jQuery.fn.FlashMessage you can do
jQuery.fn.FlashMessage=function(){
return this.each(function(){
//do some thing
});
});
//use like this, your chaining is secured
jQuery('#someElement').FlashMessage().DoSomeThingElse().SomethingMore();
if you are concerned is modifying only one element than why to use jQuery.FlashMessage, do it like myNameSpace.FlashMessage
Typically plugins on the fn namspace return a jQuery object to maintain chainability. Also they are applied to jQuery.prototype so all jQuery objects can call it.
Check out this page for a very good overview on plugin authoring: http://docs.jquery.com/Plugins/Authoring

Preventing conflict between jquery prototype/plugin methods

Suppose i have a main js file on the website that contains some code as follows:
$.fn.extend({
break: function(){
//code here
},
cut: function(){
//code here
},
// ...many other methods
});
and i use it like so:
$('#mydiv').break().animate() ...
Now if i add an external jquery plugin file that also has a 'break' method, how do i prevent conflict between my $.fn methods and someone else's?
You can't.
This is why many plugins, such as jQuery UI, only add a single method to the prototype which takes an action name as a parameter.

Categories

Resources