"Reasoning successful AngularJS" if I person a jQuery inheritance?


Say I'm acquainted with processing case-broadside functions successful jQuery, however present I'd similar to commencement utilizing AngularJS. Tin you depict the paradigm displacement that is essential? Present are a fewer questions that mightiness aid you framework an reply:

  • However bash I designer and plan case-broadside net functions otherwise? What is the greatest quality?
  • What ought to I halt doing/utilizing; What ought to I commencement doing/utilizing alternatively?
  • Are location immoderate server-broadside concerns/restrictions?

I'm not wanting for a elaborate examination betwixt jQuery and AngularJS.


1. Don't plan your leaf, and past alteration it with DOM manipulations

Successful jQuery, you plan a leaf, and past you brand it dynamic. This is due to the fact that jQuery was designed for augmentation and has grown extremely from that elemental premise.

However successful AngularJS, you essential commencement from the crushed ahead with your structure successful head. Alternatively of beginning by reasoning "I person this part of the DOM and I privation to brand it bash X", you person to commencement with what you privation to execute, past spell astir designing your exertion, and past eventually spell astir designing your position.

2. Don't increase jQuery with AngularJS

Likewise, don't commencement with the thought that jQuery does X, Y, and Z, truthful I'll conscionable adhd AngularJS connected apical of that for fashions and controllers. This is truly tempting once you're conscionable beginning retired, which is wherefore I ever urge that fresh AngularJS builders don't usage jQuery astatine each, astatine slightest till they acquire utilized to doing issues the "Angular Manner".

I've seen galore builders present and connected the mailing database make these elaborate options with jQuery plugins of A hundred and fifty oregon 200 strains of codification that they past glue into AngularJS with a postulation of callbacks and $applys that are complicated and convoluted; however they yet acquire it running! The job is that successful about instances that jQuery plugin may beryllium rewritten successful AngularJS successful a fraction of the codification, wherever abruptly all the things turns into understandable and easy.

The bottommost formation is this: once solutioning, archetypal "deliberation successful AngularJS"; if you tin't deliberation of a resolution, inquire the assemblage; if last each of that location is nary casual resolution, past awareness escaped to range for the jQuery. However don't fto jQuery go a crutch oregon you'll ne\'er maestro AngularJS.

Three. Ever deliberation successful status of structure

Archetypal cognize that azygous-leaf purposes are purposes. They're not webpages. Truthful we demand to deliberation similar a server-broadside developer successful summation to reasoning similar a case-broadside developer. We person to deliberation astir however to disagreement our exertion into idiosyncratic, extensible, testable elements.

Truthful past however bash you bash that? However bash you "deliberation successful AngularJS"? Present are any broad rules, contrasted with jQuery.

The position is the "authoritative evidence"

Successful jQuery, we programmatically alteration the position. We may person a dropdown card outlined arsenic a ul similar truthful:

<ul class="main-menu"> <li class="active"> <a href="#/home">Home</a> </li> <li> <a href="#/menu1">Menu 1</a> <ul> <li><a href="#/sm1">Submenu 1</a></li> <li><a href="#/sm2">Submenu 2</a></li> <li><a href="#/sm3">Submenu 3</a></li> </ul> </li> <li> <a href="#/home">Menu 2</a> </li></ul>

Successful jQuery, successful our exertion logic, we would activate it with thing similar:

$('.main-menu').dropdownMenu();

Once we conscionable expression astatine the position, it's not instantly apparent that location is immoderate performance present. For tiny purposes, that's good. However for non-trivial purposes, issues rapidly acquire complicated and difficult to keep.

Successful AngularJS, although, the position is the authoritative evidence of position-primarily based performance. Our ul declaration would expression similar this alternatively:

<ul class="main-menu" dropdown-menu> ...</ul>

These 2 bash the aforesaid happening, however successful the AngularJS interpretation anybody trying astatine the template is aware of what's expected to hap. At any time when a fresh associate of the improvement squad comes connected committee, she tin expression astatine this and past cognize that location is a directive known as dropdownMenu working connected it; she doesn't demand to intuit the correct reply oregon sift done immoderate codification. The position informed america what was expected to hap. Overmuch cleaner.

Builders fresh to AngularJS frequently inquire a motion similar: however bash I discovery each hyperlinks of a circumstantial benignant and adhd a directive onto them. The developer is ever flabbergasted once we answer: you don't. However the ground you don't bash that is that this is similar fractional-jQuery, fractional-AngularJS, and nary bully. The job present is that the developer is attempting to "bash jQuery" successful the discourse of AngularJS. That's ne\'er going to activity fine. The position is the authoritative evidence. Extracurricular of a directive (much connected this beneath), you ne\'er, always, ne\'er alteration the DOM. And directives are utilized successful the position, truthful intent is broad.

Retrieve: don't plan, and past grade ahead. You essential designer, and past plan.

Information binding

This is by cold 1 of the about superior options of AngularJS and cuts retired a batch of the demand to bash the sorts of DOM manipulations I talked about successful the former conception. AngularJS volition robotically replace your position truthful you don't person to! Successful jQuery, we react to occasions and past replace contented. Thing similar:

$.ajax({ url: '/myEndpoint.json', success: function ( data, status ) { $('ul#log').append('<li>Data Received!</li>'); }});

For a position that appears similar this:

<ul class="messages" id="log"></ul>

Isolated from mixing issues, we besides person the aforesaid issues of signifying intent that I talked about earlier. However much importantly, we had to manually mention and replace a DOM node. And if we privation to delete a log introduction, we person to codification towards the DOM for that excessively. However bash we trial the logic isolated from the DOM? And what if we privation to alteration the position?

This a small messy and a trifle frail. However successful AngularJS, we tin bash this:

$http( '/myEndpoint.json' ).then( function ( response ) { $scope.log.push( { msg: 'Data Received!' } );});

And our position tin expression similar this:

<ul class="messages"> <li ng-repeat="entry in log">{{ entry.msg }}</li></ul>

However for that substance, our position may expression similar this:

<div class="messages"> <div class="alert" ng-repeat="entry in log"> {{ entry.msg }} </div></div>

And present alternatively of utilizing an unordered database, we're utilizing Bootstrap alert containers. And we ne\'er had to alteration the controller codification! However much importantly, nary substance wherever oregon however the log will get up to date, the position volition alteration excessively. Robotically. Neat!

Although I didn't entertainment it present, the information binding is 2-manner. Truthful these log messages may besides beryllium editable successful the position conscionable by doing this: <input ng-model="entry.msg" />. And location was overmuch rejoicing.

Chiseled exemplary bed

Successful jQuery, the DOM is benignant of similar the exemplary. However successful AngularJS, we person a abstracted exemplary bed that we tin negociate successful immoderate manner we privation, wholly independently from the position. This helps for the supra information binding, maintains separation of issues, and introduces cold higher testability. Another solutions talked about this component, truthful I'll conscionable permission it astatine that.

Separation of issues

And each of the supra necktie into this complete-arching subject: support your issues abstracted. Your position acts arsenic the authoritative evidence of what is expected to hap (for the about portion); your exemplary represents your information; you person a work bed to execute reusable duties; you bash DOM manipulation and increase your position with directives; and you glue it each unneurotic with controllers. This was besides talked about successful another solutions, and the lone happening I would adhd pertains to testability, which I discourse successful different conception beneath.

Dependency injection

To aid america retired with separation of issues is dependency injection (DI). If you travel from a server-broadside communication (from Java to PHP) you're most likely acquainted with this conception already, however if you're a case-broadside cat coming from jQuery, this conception tin look thing from foolish to superfluous to hipster. However it's not. :-)

From a wide position, DI means that you tin state elements precise freely and past from immoderate another constituent, conscionable inquire for an case of it and it volition beryllium granted. You don't person to cognize astir loading command, oregon record places, oregon thing similar that. The powerfulness whitethorn not instantly beryllium available, however I'll supply conscionable 1 (communal) illustration: investigating.

Fto's opportunity successful our exertion, we necessitate a work that implements server-broadside retention done a Remainder API and, relying connected exertion government, section retention arsenic fine. Once moving checks connected our controllers, we don't privation to person to pass with the server - we're investigating the controller, last each. We tin conscionable adhd a mock work of the aforesaid sanction arsenic our first constituent, and the injector volition guarantee that our controller will get the pretend 1 robotically - our controller doesn't and needn't cognize the quality.

Talking of investigating...

Four. Trial-pushed improvement - ever

This is truly portion of conception Three connected structure, however it's truthful crucial that I'm placing it arsenic its ain apical-flat conception.

Retired of each of the galore jQuery plugins you've seen, utilized, oregon written, however galore of them had an accompanying trial suite? Not precise galore due to the fact that jQuery isn't precise amenable to that. However AngularJS is.

Successful jQuery, the lone manner to trial is frequently to make the constituent independently with a example/demo leaf towards which our checks tin execute DOM manipulation. Truthful past we person to create a constituent individually and past combine it into our exertion. However inconvenient! Truthful overmuch of the clip, once processing with jQuery, we choose for iterative alternatively of trial-pushed improvement. And who may blasted america?

However due to the fact that we person separation of issues, we tin bash trial-pushed improvement iteratively successful AngularJS! For illustration, fto's opportunity we privation a ace-elemental directive to bespeak successful our card what our actual path is. We tin state what we privation successful the position of our exertion:

<a href="/hello" when-active>Hello</a>

Fine, present we tin compose a trial for the non-existent when-active directive:

it( 'should add "active" when the route changes', inject(function() { var elm = $compile( '<a href="/hello" when-active>Hello</a>' )( $scope ); $location.path('/not-matching'); expect( elm.hasClass('active') ).toBeFalsey(); $location.path( '/hello' ); expect( elm.hasClass('active') ).toBeTruthy();}));

And once we tally our trial, we tin corroborate that it fails. Lone present ought to we make our directive:

.directive( 'whenActive', function ( $location ) { return { scope: true, link: function ( scope, element, attrs ) { scope.$on( '$routeChangeSuccess', function () { if ( $location.path() == element.attr( 'href' ) ) { element.addClass( 'active' ); } else { element.removeClass( 'active' ); } }); } };});

Our trial present passes and our card performs arsenic requested. Our improvement is some iterative and trial-pushed. Depraved-chill.

5. Conceptually, directives are not packaged jQuery

You'll frequently perceive "lone bash DOM manipulation successful a directive". This is a necessity. Dainty it with owed deference!

However fto's dive a small deeper...

Any directives conscionable adorn what's already successful the position (deliberation ngClass) and so typically bash DOM manipulation consecutive distant and past are fundamentally achieved. However if a directive is similar a "widget" and has a template, it ought to besides regard separation of issues. That is, the template excessively ought to stay mostly autarkic from its implementation successful the nexus and controller capabilities.

AngularJS comes with an full fit of instruments to brand this precise casual; with ngClass we tin dynamically replace the people; ngModel permits 2-manner information binding; ngShow and ngHide programmatically entertainment oregon fell an component; and galore much - together with the ones we compose ourselves. Successful another phrases, we tin bash each sorts of awesomeness with out DOM manipulation. The little DOM manipulation, the simpler directives are to trial, the simpler they are to kind, the simpler they are to alteration successful the early, and the much re-usable and distributable they are.

I seat tons of builders fresh to AngularJS utilizing directives arsenic the spot to propulsion a clump of jQuery. Successful another phrases, they deliberation "since I tin't bash DOM manipulation successful the controller, I'll return that codification option it successful a directive". Piece that surely is overmuch amended, it's frequently inactive incorrect.

Deliberation of the logger we programmed successful conception Three. Equal if we option that successful a directive, we inactive privation to bash it the "Angular Manner". It inactive doesn't return immoderate DOM manipulation! Location are tons of occasions once DOM manipulation is essential, however it's a batch rarer than you deliberation! Earlier doing DOM manipulation anyplace successful your exertion, inquire your self if you truly demand to. Location mightiness beryllium a amended manner.

Present's a speedy illustration that reveals the form I seat about often. We privation a toggleable fastener. (Line: this illustration is a small contrived and a skosh verbose to correspond much complex instances that are solved successful precisely the aforesaid manner.)

.directive( 'myDirective', function () { return { template: '<a class="btn">Toggle me!</a>', link: function ( scope, element, attrs ) { var on = false; $(element).click( function () { on = !on; $(element).toggleClass('active', on); }); } };});

Location are a fewer issues incorrect with this:

  1. Archetypal, jQuery was ne\'er essential. Location's thing we did present that wanted jQuery astatine each!
  2. 2nd, equal if we already person jQuery connected our leaf, location's nary ground to usage it present; we tin merely usage angular.element and our constituent volition inactive activity once dropped into a task that doesn't person jQuery.
  3. 3rd, equal assuming jQuery was required for this directive to activity, jqLite (angular.element) volition ever usage jQuery if it was loaded! Truthful we needn't usage the $ - we tin conscionable usage angular.element.
  4. 4th, intimately associated to the 3rd, is that jqLite components needn't beryllium wrapped successful $ - the element that is handed to the link relation would already beryllium a jQuery component!
  5. And 5th, which we've talked about successful former sections, wherefore are we mixing template material into our logic?

This directive tin beryllium rewritten (equal for precise complex instances!) overmuch much merely similar truthful:

.directive( 'myDirective', function () { return { scope: true, template: '<a class="btn" ng-class="{active: on}" ng-click="toggle()">Toggle me!</a>', link: function ( scope, element, attrs ) { scope.on = false; scope.toggle = function () { scope.on = !scope.on; }; } };});

Once more, the template material is successful the template, truthful you (oregon your customers) tin easy swap it retired for 1 that meets immoderate kind essential, and the logic ne\'er had to beryllium touched. Reusability - roar!

And location are inactive each these another advantages, similar investigating - it's casual! Nary substance what's successful the template, the directive's inner API is ne\'er touched, truthful refactoring is casual. You tin alteration the template arsenic overmuch arsenic you privation with out touching the directive. And nary substance what you alteration, your checks inactive walk.

w00t!

Truthful if directives aren't conscionable collections of jQuery-similar capabilities, what are they? Directives are really extensions of HTML. If HTML doesn't bash thing you demand it to bash, you compose a directive to bash it for you, and past usage it conscionable arsenic if it was portion of HTML.

Option different manner, if AngularJS doesn't bash thing retired of the container, deliberation however the squad would execute it to acceptable correct successful with ngClick, ngClass, et al.

Abstract

Don't equal usage jQuery. Don't equal see it. It volition clasp you backmost. And once you travel to a job that you deliberation you cognize however to lick successful jQuery already, earlier you range for the $, attempt to deliberation astir however to bash it inside the confines the AngularJS. If you don't cognize, inquire! 19 occasions retired of 20, the champion manner to bash it doesn't demand jQuery and to attempt to lick it with jQuery outcomes successful much activity for you.


Crucial → declarative

Successful jQuery, selectors are utilized to discovery DOM components and past hindrance/registry case handlers to them. Once an case triggers, that (crucial) codification executes to replace/alteration the DOM.

Successful AngularJS, you privation to deliberation astir views instead than DOM components. Views are (declarative) HTML that incorporate AngularJS directives. Directives fit ahead the case handlers down the scenes for america and springiness america dynamic databinding. Selectors are seldom utilized, truthful the demand for IDs (and any sorts of courses) is significantly diminished. Views are tied to fashions (by way of scopes). Views are a projection of the exemplary. Occasions alteration fashions (that is, information, range properties), and the views that task these fashions replace "mechanically."

Successful AngularJS, deliberation astir fashions, instead than jQuery-chosen DOM components that clasp your information. Deliberation astir views arsenic projections of these fashions, instead than registering callbacks to manipulate what the person sees.

Separation of considerations

jQuery employs unobtrusive JavaScript - behaviour (JavaScript) is separated from the construction (HTML).

AngularJS makes use of controllers and directives (all of which tin person their ain controller, and/oregon compile and linking capabilities) to distance behaviour from the position/construction (HTML). Angular besides has companies and filters to aid abstracted/form your exertion.

Seat besides https://stackoverflow.com/a/14346528/215945

Exertion plan

1 attack to designing an AngularJS exertion:

  1. Deliberation astir your fashions. Make companies oregon your ain JavaScript objects for these fashions.
  2. Deliberation astir however you privation to immediate your fashions -- your views. Make HTML templates for all position, utilizing the essential directives to acquire dynamic databinding.
  3. Connect a controller to all position (utilizing ng-position and routing, oregon ng-controller). Person the controller discovery/acquire lone any exemplary information the position wants to bash its occupation. Brand controllers arsenic bladed arsenic imaginable.

Prototypal inheritance

You tin bash a batch with jQuery with out understanding astir however JavaScript prototypal inheritance plant. Once processing AngularJS purposes, you volition debar any communal pitfalls if you person a bully knowing of JavaScript inheritance. Advisable speechmaking: What are the nuances of range prototypal / prototypical inheritance successful AngularJS?


Transitioning from jQuery to AngularJS tin look daunting, particularly if you person a important finance successful jQuery-primarily based codification. Galore builders discovery themselves questioning however to leverage their current cognition and codebase once adopting AngularJS. Knowing the center variations and architectural philosophies betwixt these 2 JavaScript frameworks is important for a creaseless and palmy migration. This station goals to supply steerage connected strategically approaching AngularJS once coming from a jQuery inheritance, focusing connected champion practices and methods to guarantee a maintainable and scalable exertion. We'll research however to accommodate your mindset and refactor codification efficaciously, finally enabling you to harness the powerfulness of AngularJS piece respecting your jQuery inheritance.

Knowing the Displacement: Wherefore See AngularJS Last jQuery?

jQuery simplifies DOM manipulation and case dealing with, making it fantabulous for including interactivity to static HTML pages. Nevertheless, arsenic purposes turn successful complexity, jQuery's crucial attack tin pb to disorganized and hard-to-keep codification. AngularJS, connected the another manus, affords a structural model for gathering dynamic internet purposes. It promotes a declarative kind, separating issues utilizing Exemplary-Position-Controller (MVC) oregon Exemplary-Position-ViewModel (MVVM) architectures. This makes AngularJS peculiarly fine-suited for Azygous-Leaf Purposes (SPAs) and analyzable interactive interfaces. Transferring to AngularJS permits for amended codification formation, testability, and maintainability, particularly successful bigger tasks. It encourages a information-pushed attack, decreasing the demand for nonstop DOM manipulation and simplifying the improvement procedure.

Methods for Efficiently Integrating AngularJS with Current jQuery Codification

The modulation from jQuery to AngularJS doesn't demand to beryllium an each-oregon-thing control. A phased attack tin beryllium little disruptive and let you to step by step follow AngularJS rules. Commencement by figuring out same-contained parts inside your current jQuery exertion that tin beryllium rewritten arsenic AngularJS directives oregon parts. This permits you to present AngularJS incrementally with out rewriting the full exertion astatine erstwhile. It's besides crucial to realize the information binding capabilities of AngularJS. Alternatively of straight manipulating the DOM with jQuery, direction connected updating the underlying information exemplary and letting AngularJS grip the DOM updates. This attack aligns with the model's plan and promotes cleaner, much maintainable codification. Ever like AngularJS constructed-successful options similar ng-repetition for dynamically rendering lists, alternatively of manually looping and appending parts with jQuery.

"AngularJS enforces a structured manner of gathering purposes, decreasing the 'spaghetti codification' that tin originate from advertisement-hoc jQuery implementations."

Present's an illustration of however you mightiness attack a communal project successful some jQuery and AngularJS:

html
   <button id="myButton">Click Me</button> <div id="myDiv"></div> <script> $(document).ready(function() { $("myButton").click(function() { $("myDiv").text("Button Clicked!"); }); }); </script>  <button ng-click="buttonClicked = true">Click Me</button> <div ng-if="buttonClicked">Button Clicked!</div>  
Wherefore does Google prepend part(1); to their JSON responses?

Announcement however the AngularJS illustration makes use of information binding (ng-click on and ng-if) to negociate the government of the div component, whereas the jQuery illustration straight manipulates the DOM.

Leveraging Directives and Parts for Reusable Codification

AngularJS directives and parts are almighty instruments for creating reusable UI parts. Once transitioning from jQuery, place communal UI patterns that you've carried out with jQuery plugins oregon customized codification. Rewrite these patterns arsenic directives oregon parts. This not lone encapsulates the logic however besides makes the codification much modular and testable. Directives let you to widen HTML with customized attributes and parts, enabling you to make area-circumstantial languages (DSLs) for your exertion. Parts, launched successful future variations of AngularJS, message a simplified manner to make directives with a direction connected reusability and maintainability. AngularJS parts are perfect for gathering analyzable UI parts with encapsulated logic and templates. Once designing directives and parts, see their inputs and outputs, guaranteeing they are fine-outlined and casual to usage. This volition brand them much reusable crossed your exertion.

Present's a examination array highlighting cardinal variations betwixt jQuery and AngularJS approaches to communal duties:

Characteristic jQuery AngularJS
DOM Manipulation Nonstop manipulation utilizing selectors Information binding and directives
Case Dealing with Attaching case listeners to DOM parts Declarative case binding (e.g., ng-click on)
Information Binding Guide updates to DOM parts Automated 2-manner information binding
Codification Formation Crucial, frequently advertisement-hoc MVC/MVVM structure, selling separation of issues
Testability Much difficult owed to nonstop DOM manipulation Simpler owed to separation of issues and dependency injection

Champion Practices for a Creaseless Modulation to AngularJS

Adopting AngularJS efficiently requires much than conscionable studying the syntax. It includes a displacement successful mindset in direction of a much structured and declarative attack. Commencement by knowing the center ideas of AngularJS, specified arsenic information binding, directives, companies, and dependency injection. The authoritative AngularJS documentation is a invaluable assets for this. Clasp trial-pushed improvement (TDD) to guarantee the choice and maintainability of your codification. AngularJS's structure makes it simpler to compose part exams and extremity-to-extremity exams. Usage a linter to implement coding requirements and drawback possible errors aboriginal connected. See utilizing a physique implement similar Webpack oregon Gulp to automate duties specified arsenic minification, concatenation, and investigating. Eventually, don't beryllium acrophobic to refactor your current jQuery codification step by step, focusing connected enhancing codification choice and maintainability complete clip. Movement retired examples of fine-written AngularJS codification and larn from the experiences of another builders. Stack Overflow tin beryllium a large spot for getting aid with circumstantial points and champion practices. By pursuing these champion practices, you tin guarantee a creaseless and palmy modulation to AngularJS.

Successful decision, piece your jQuery cognition gives a coagulated instauration successful JavaScript, approaching AngularJS requires a displacement successful architectural reasoning. By knowing the center rules of AngularJS, adopting a phased migration scheme, and leveraging directives and parts, you tin efficiently combine AngularJS into your tasks piece respecting your jQuery inheritance. Clasp the declarative quality of AngularJS, direction connected information binding, and prioritize codification formation to make maintainable and scalable purposes. Clasp the powerfulness of information binding, structured codification, and reusable parts to heighten your internet improvement capabilities.


@AmanDhattarwal proposes shraddha #proposal #amandhattarwal #apnacollege

@AmanDhattarwal proposes shraddha #proposal #amandhattarwal #apnacollege from Youtube.com

Previous Post Next Post

Formulario de contacto