AngularJS는 jQuery보다 나은 점은 무엇입니까? [닫은]
나는 주로 jQuery 라이브러리를 사용하고 있으며 AngularJS를 사용하기 시작했습니다. Angular를 사용 하는 방법 에 대한 몇 가지 자습서를 읽었 지만 왜, 언제 사용 해야하는지, jQuery를 사용하는 것과 비교하여 어떤 이점이 있는지 명확하지 않습니다.
Angular가 MVC를 생각하게 만드는 것 같습니다. 아마도 웹 페이지를 템플릿 + 데이터 조합으로 볼 수 있습니다. {{data bindings}}
동적 데이터가 있다고 느낄 때마다 사용 합니다. 그러면 Angular는 $ scope 핸들러를 제공하여 정적으로 또는 웹 서버 호출을 통해 채울 수 있습니다. 이것은 웹 페이지를 디자인하는 JSP 방식과 특징적으로 비슷합니다. 이것을 위해 Angular가 필요합니까?
데이터 조작을 포함 하지 않는 간단한 DOM 조작 (예 : 마우스 오버의 색상 변경, 클릭시 요소 숨기기 / 표시)의 경우 jQuery 또는 바닐라 JS로 충분하고 깨끗합니다. 이것은 있다고 가정 모델을 각의에서 MVC가 있다 페이지의 데이터를 반영 아무것도 에 영향을주지 않는, 따라서, 색상, 표시 / 숨기기와 같은 CSS 속성 등을 변경 모델 . Angular는 DOM 조작에서 jQuery 또는 vanilla JS보다 장점이 있습니까?
jQuery가 플러그인과 함께 할 수있는 것과 비교할 때 Angular가 개발에 유용한 것은 무엇입니까?
데이터 바인딩
귀하는 웹 페이지를 만들고, 동적 데이터가 있다고 생각 될 때마다 {{data bindings}}를 계속 사용합니다. 그러면 Angular는 $ scope 핸들러를 제공하며이를 통해 (정적으로 또는 웹 서버 호출을 통해) 채울 수 있습니다.
이것은 데이터 바인딩에 대한 이해입니다. 나는 당신이 그것을 다운 생각합니다.
DOM 조작
데이터 조작을 포함하지 않는 간단한 DOM 조작 (예 : 마우스 오버의 색상 변경, 클릭시 요소 숨기기 / 표시)의 경우 jQuery 또는 구식 js로 충분하고 깨끗합니다. 이것은 angular의 mvc의 모델이 페이지의 데이터를 반영하는 것으로 가정하므로 색상, 표시 / 숨기기 등과 같은 CSS 속성은 모델에 영향을 미치지 않습니다.
여기서는 "단순한"DOM 조작이 더 깨끗하다는 점을 알 수 있지만, 실제로는 "단순"해야합니다. DOM 조작은 Angular가 실제로 빛나는 데이터 바인딩과 같은 영역 중 하나라고 생각합니다. 이것을 이해하면 Angular가 뷰를 어떻게 고려하는지 알 수 있습니다.
먼저 Angular 방식과 DOM 조작에 대한 바닐라 js 접근 방식을 비교하여 시작하겠습니다. 전통적으로 우리는 HTML을 아무것도하지 않는 것으로 생각하고 그렇게 작성합니다. 따라서 "onclick"과 같은 인라인 js는 "doing"이 아닌 HTML의 컨텍스트에 "doing"을 넣기 때문에 나쁜 습관입니다. 각도는 그 개념을 머리에 뒤집습니다. 뷰를 작성할 때 HTML은 많은 것을 "할"수 있다고 생각합니다. 이 기능은 각도 지시문에 추상화되어 있지만 이미 존재하거나 작성했으면 "어떻게"수행했는지 고려할 필요가 없습니다.이 "확장 된"HTML에서 제공되는 기능 만 사용하면됩니다. 각도를 사용하면 사용할 수 있습니다. 또한 모든 뷰 로직이 실제로 뷰에 포함되어 있음을 의미합니다. 자바 스크립트 파일에 없습니다. 다시 말하지만, 자바 스크립트 파일에 작성된 지시문이 HTML의 기능을 향상시키는 것으로 간주 될 수 있으므로 DOM이 자신을 조작하는 것에 대해 걱정하게합니다. 간단한 예를 들어 설명하겠습니다.
이것은 우리가 사용하고자하는 마크 업입니다. 나는 직관적 인 이름을 주었다.
<div rotate-on-click="45"></div>
먼저, 맞춤 Angular Directive를 통해 HTML에 이러한 기능을 제공했다면 이미 완료 되었다고 언급하고 싶습니다 . 그것은 신선한 공기의 숨결입니다. 잠시 후에 그것에 대해 더 자세히 설명합니다.
jQuery로 구현
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
Angular를 사용한 구현
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
General differences.
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular and jQuery can't reasonably be compared.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Why use a framework?
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
- Templating
- Data-binding
- routing (single page app)
- clean, modular, reusable architecture
- security
- additional functions/features for convenience
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Angular (revisited).
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
DOM reference.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
MVW Architecure / Modules / Dependency Injection
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
It isn't easy to make things "work" in Angular.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
참고URL : https://stackoverflow.com/questions/18414012/what-does-angularjs-do-better-than-jquery
'Programming' 카테고리의 다른 글
Webpack.config index.html을 dist 폴더에 복사하는 방법 (0) | 2020.05.26 |
---|---|
가능한 두 테이블 중 하나에 MySQL 외래 키를 수행 할 수 있습니까? (0) | 2020.05.26 |
Spring MVC : GET @RequestParam과 같은 복잡한 객체 (0) | 2020.05.26 |
curl에 대한 요청 헤더를 어떻게 설정합니까? (0) | 2020.05.26 |
경고 : 보호되지 않은 개인 키 파일! (0) | 2020.05.26 |