简体   繁体   中英

Strategies for Combining Existing JavaScript into AngularJS

I'll preface this with that I'm new to AngularJS and still learning the best practices.

What is the best practice for integrating existing JavaScript features/plugins/code into an Angular application?

For instance when should the integrated JavaScript fire if a normal implementation fires when the DOM is ready?

Or should it be rewritten as a directive or can the JavaScript be used without any changes?

In my experience I have tried to follow instructions for using scripts such as JVFloat or SkeuoCard with limited success out of the box. I've been able to hack them into my code, but I'm not sure what the best practice would be.

Angular is a fairly large script, but it helps drastically reduce the amount of code needed for most projects. That said, it is likely that other libraries/plugins you are considering will be much larger than if you were to rewrite them using the power of angular. The Angular devs strongly recommend taking full advantage of the framework to offset its large size. The theory is that if you do this properly, Angular will save you bytes, not cost them.

To cleanly use external plugins, you'll need to wrap them as angular directives, so there is a bit of adaptation necessary that point. I have actually seen this done in a manner that was more verbose than if the developer has not used the plugin at all. It's not that it required a lot of code to wrap the plugin as a directive, it's just that the functionality of the plugin is so easily reproducible with Angular that the plugin was nearly useless.

Regarding DOM ready: Thinking the Angular way has a bit of magic about it. Because of the power of directives, $watch , promises, and data-binding, you don't think as much in terms of timing as you do relationship. If all is done well, the updates and behaviors will occur when they can (data is served, things are loaded, etc) and everything is updated automatically. Just build a simple app and you'll quickly see that Angular makes complex systems a cinch.

You might also be interested in this previous answer of mine: What does AngularJS do better than jQuery?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM