“Thinking in AngularJS”如果我有一个jQuery的背景? [英] "Thinking in AngularJS" if I have a jQuery background?

查看:349
本文介绍了“Thinking in AngularJS”如果我有一个jQuery的背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我熟悉在 jQuery 中开发客户端应用程序,但现在我想开始使用 AngularJS 。你可以描述必要的范式转变吗?以下是一些可能有助于您构建答案的问题:




  • 如何以不同的方式构建和设计客户端Web应用程序?最大的区别是什么?

  • 我该停止做什么/使用?

  • 是否有任何服务器端注意事项/限制?



我不是在 jQuery AngularJS 之间的详细比较。

解决方案

1。不要设计您的页面,然后使用 DOM 操作来更改页面



在jQuery中,您设计一个页面,然后使其成为动态的。这是因为jQuery是为了增强而设计的,并且从这个简单的前提变得非常难以置信。



但是在AngularJS中,您必须从头开始考虑您的架构。不要以我有这块DOM,我想做它做X开始,你必须从你想要完成的事情开始,然后去设计你的应用程序,然后再去设计你的视图。



2。不要用AngularJS来增加jQuery



同样,不要从jQuery做X,Y和Z的想法开始,所以我只需要在顶部添加AngularJS的模型和控制器。这是真正的真的很诱人,当你刚刚开始,这就是为什么我总是建议,新的AngularJS开发人员根本不使用jQuery,至少直到他们习惯做Angular Way



我在这里看到很多开发人员,在邮件列表中创建了这些精心设计的解决方案,其中包含150或200行代码的jQuery插件,然后粘贴到AngularJS中回调的集合和 $ apply s是令人困惑和复杂的;但他们最终会让它工作!问题是,在大多数案例中,jQuery插件可以在AngularJS中以一小部分代码重写,突然间一切都变得可理解和直接。



底线是这样的:解决时,首先在AngularJS中考虑;如果你不能想到一个解决方案,请问社区;如果所有这一切都没有简单的解决方案,那么可以随时获得jQuery。但是不要让jQuery成为拐杖,否则你永远不会掌握AngularJS。



3。始终以建筑学思考



首先知道单页应用程序应用程序。他们是不是网页。因此,我们需要像服务器端开发人员另外想一想像客户端开发人员一样思考。我们必须考虑如何将我们的应用程序分成个别的,可扩展的,可测试的组件。



那么你怎么这样做?你如何在AngularJS中思考?这里有一些一般的原则,与jQuery对比。



视图是官方记录



在jQuery中我们以编程方式更改视图。我们可以有一个下拉菜单定义为 ul ,如下所示:

 < ul class =main-menu> 
< li class =active>
< a href =#/ home>首页< / a>
< / li>
< li>
< a href =#/ menu1>菜单1< / a>
< ul>
< li>< a href =#/ sm1>子菜单1< / a>< / li>
< li>< a href =#/ sm2>子菜单2< / a>< / li>
< li>< a href =#/ sm3>子菜单3< / a>< / li>
< / ul>
< / li>
< li>
< a href =#/ home>菜单2< / a>
< / li>
< / ul>

在jQuery中,在我们的应用程序逻辑中,我们将使用以下操作激活它:

  $('。主菜单')。 

当我们看看视图时,并不是很明显这里有任何功能。对于小的应用程序,没关系。但是对于非平凡的应用程序,事情很快就会变得混乱,很难维护。



然而,在AngularJS中,视图是基于视图的功能的官方记录。我们的 ul 声明将改为:

 < ul class =main-menu下拉菜单> 
...
< / ul>

这两个做同样的事情,但是在AngularJS版本中,任何看模板的人都知道应该怎么做发生。每当一个开发团队的新成员进来时,她可以看这个,然后知道有一个叫做 dropdownMenu 的指令;她不需要直觉正确的答案或筛选任何代码。这个观点告诉我们应该发生什么事情。更清洁。



AngularJS的开发人员经常提出以下问题:如何查找特定类型的所有链接并在其上添加指令。当我们回复的时候,开发人员总是被夸张:你不会。但是你不这么做的原因是这就像半jQuery,半角AngularJS,没有好处。这里的问题是开发人员试图在AngularJS的上下文中做jQuery。这永远不会奏效。视图 是官方记录。在一个指令之外(更多在这里),永远永远不会更改DOM。并且在视图中应用指令,所以意图很清楚。



记住:不要设计,然后标记。你必须建筑师,然后设计。



数据绑定



这是迄今为止最棒的功能之一的AngularJS,并削减了很多需要做上一节中提到的DOM操作。 AngularJS会自动更新你的视图,所以你不必!在jQuery中,我们回应事件,然后更新内容。一些东西:

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

对于如下视图:



< pre class =lang-html prettyprint-override> < ul class =messagesid =log>
< / ul>

除了混合关注,我们也有同样的问题表示我之前提到的意图。但更重要的是,我们必须手动引用和更新DOM节点。如果我们要删除日志条目,那么我们也必须针对DOM进行编码。我们如何测试除了DOM之外的逻辑?那么如果我们想改变演示文稿,那怎么办?



这个有点乱七八糟的虚弱。但是在AngularJS中,我们可以这么做:

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

我们的视图可能如下所示:



< pre class =lang-html prettyprint-override> < ul class =messages>
< li ng-repeat =log in> {{entry.msg}}< / li>
< / ul>

但是对于这个问题,我们的看法可能如下所示:

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

现在,而不是使用无序列表,我们使用的是Bootstrap警报框。而我们从来没有改变控制器代码!但更重要的是,无论 如何更新日志,视图也将改变。自动。整洁!



虽然我没有在这里显示,但数据绑定是双向的。因此,这些日志消息也可以在视图中进行编辑,只需执行以下操作:< input ng-model =entry.msg/> 。还有很多欣喜。



不同的模型层



在jQuery中,DOM类似于模型。但在AngularJS中,我们有一个单独的模型层,我们可以以任何方式管理,完全独立于视图。这有助于上述数据绑定,维护分离关注,并引入更大的可测试性。其他答案提到这一点,所以我只是把它留在那里。



分离问题



以上所有这些都与这个超凡的主题相结合:将您的疑虑分开。您的观点是作为正在发生的事情(大部分)的正式记录;您的模型代表您的数据;你有一个服务层来执行可重用的任务;你做DOM操作,并用指令增加你的观点;并将其与控制器粘合在一起。在其他答案中也提到了这一点,我唯一可以添加的是可测试性,我在下面的另一节讨论。



依赖注入



为了帮助我们解决问题,请依赖注入( DI)。如果您从服务器端语言(从 Java 转到 PHP )你可能已经熟悉了这个概念,但如果你是来自jQuery的客户端的人,这个概念似乎从愚蠢到多余到时髦都可以。但不是。 : - )



从广义的角度来说,DI意味着您可以非常自由地声明组件,然后从任何其他组件声明组件,只需要一个实例,理所当然的。您不必了解加载订单或文件位置,或任何类似的东西。权力可能不会立即显现,但我只提供一个(常见的)示例:测试。



我们在应用程序中需要一个实现服务器的服务通过 REST API进行存储,并根据应用程序状态,同时存储本地存储。在我们的控制器上运行测试时,我们不想与服务器进行通信 - 毕竟我们正在测试控制器。我们可以添加与原始组件相同名称的模拟服务,并且注射器将确保我们的控制器自动获得假的控制器 - 我们的控制器不会也不需要知道差异。



说到测试...



4。测试驱动的开发 - 总是



这是第3部分关于架构的一部分,但它非常重要,我把它作为自己的顶级部分。



在你看过,使用或写过的许多jQuery插件中,有多少人有一个随附的测试套件?不是很多,因为jQuery不是很适合那个。但是AngularJS是。



在jQuery中,唯一的测试方法通常是使用我们的测试可以执行DOM操作的示例/演示页面独立创建组件。那么我们必须单独开发一个组件,然后将集成到我们的应用程序中。多么不方便很多时候,在用jQuery开发的时候,我们选择迭代而不是测试驱动开发。谁可以责怪我们?



但是,由于我们有分歧的问题,我们可以在AngularJS中迭代地进行测试驱动的开发!例如,假设我们需要一个超简单的指令来在菜单中指出我们当前的路由。我们可以在我们的应用程序的视图中声明我们想要的内容:

 < a href = / hellowhen-active> Hello< / a> 

好的,现在我们可以为不存在的活动指令:

 它('应该添加活动路由更改',注意($($ {
var elm = $ compile('< a href =/ hellowhen-active> Hello< / a> b
$ location.path('/ not-matching');
expect(elm.hasClass('active')).toBeFalsey();

$ location.path ('/ hello');
expect(elm.hasClass('active')).toBeTruthy();
}));

当我们运行测试时,我们可以确认它失败。只有现在我们应该创建我们的指令:

  .directive('whenActive',function ){
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');
}
});
}
};
});

我们的测试现在通过菜单按要求执行。我们的开发是 和测试驱动。恶作剧。



5。在概念上,指令是打包jQuery



您经常会听到只在指令中执行DOM操作。 这是一个必需品。



但是让我们深入一下...



一些指令只是装饰视图中已经有的指令(认为 ngClass ),因此有时会立即执行DOM操作,然后基本完成。但是,如果一个指令就像一个小部件,并且有一个模板,那么应该尊重分离问题。也就是说,模板 应该在很大程度上独立于链接和控制器功能的实现。



AngularJS带有一整套工具使这很容易使用 ngClass 我们可以动态更新类; ngModel 允许双向数据绑定; ngShow ngHide 以编程方式显示或隐藏元素;还有更多的 - 包括我们自己写的那些。换句话说,我们可以在不使用 DOM操作的情况下执行各种各样的awesomeness。更少的DOM操作,更容易的指令是测试,更容易的风格,他们将来更容易变化,更可重复使用和可分发。



我看到许多开发人员使用指令作为抛出一堆jQuery的地方,而使用AngularJS。换句话说,他们认为由于我无法在控制器中执行DOM操作,所以我将把该代码放在一个指令中。虽然这肯定好多了,但是通常仍然错误。



想想我们在第3节中编写的记录器。即使我们把它放在一个指令,我们仍然想做这个角色。它仍然不采取任何DOM操纵!有很多次DOM操作是必要的,但它是一个比你想象的更少的在您的应用程序中执行DOM操作之前,请问自己是否真的需要。可能会有一个更好的方法。



这是一个快速的例子,显示了我最常看到的模式。我们想要一个可切换的按钮。 (注意:这个例子是有点诡异的,并且是一个空白的,用来表示更复杂的情况,以完全相同的方式解决。)

  .directive('myDirective',function(){
return {
template:'< a class =btn>切换我!< / a> ;
link:function(scope,element,attrs){
var on = false;

$(element).click(function(){
on =!on;
$(element).toggleClass('active',on);
});
}
};
});

这里有一些问题:


  1. 首先,jQuery从来没有必要。没有我们在这里完成所需的jQuery!

  2. 其次,即使我们的页面上已经有jQuery,也没有理由在这里使用;我们可以简单地使用 angular.element ,当我们的组件丢失到没有jQuery的项目中时,我们的组件仍然可以工作。

  3. 第三即使这个指令需要jQuery ,jqLit​​e( angular.element )将永远使用jQuery if它被加载!所以我们不需要使用 $ - 我们可以使用 angular.element

  4. 第四,与第三个密切相关的是,jqLit​​e元素不需要包裹在 $ - 元素已传递给链接函数将已经是一个jQuery元素!第五,我们在前面的部分提到过,为什么我们将模板的东西混合到我们的逻辑中?

这个指令可以被重写(即使是非常复杂的情况!)更像这样:

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

scope.toggle = function(){
scope.on =!scope.on;
};
}
};
});

同样,模板的东西在模板中,所以你(或你的用户)可以轻松地交换可以满足任何必要的风格,而且逻辑从来没有被触动过。可重用性 - 繁荣!



还有所有其他好处,如测试 - 很容易!无论模板中的内容如何,​​该指令的内部API都不会被触摸,所以重构很容易。您可以根据需要更改模板,而无需触摸该指令。无论你改变什么,你的测试仍然通过。



w00t!



所以如果指令不是只是jQuery类功能的集合,它们是什么?指令实际上是 HTML 的扩展。如果HTML不执行你需要做的事情,你会为你写一个指令,然后使用它就像它是HTML的一部分。



ngClick , ngClass 等。



摘要



甚至不要使用jQuery。甚至不包括它。它会阻止你回来当你遇到一个问题,你认为你知道如何在jQuery中解决,在你达到 $ 之前,尝试考虑如何在限制内AngularJS。如果你不知道,请问! 20次中的19次,最好的方法是不需要jQuery,并尝试用jQuery来解决它,为您提供更多的工作。


Suppose I'm familiar with developing client-side applications in jQuery, but now I'd like to start using AngularJS. Can you describe the paradigm shift that is necessary? Here are a few questions that might help you frame an answer:

  • How do I architect and design client-side web applications differently? What is the biggest difference?
  • What should I stop doing/using; What should I start doing/using instead?
  • Are there any server-side considerations/restrictions?

I'm not looking for a detailed comparison between jQuery and AngularJS.

解决方案

1. Don't design your page, and then change it with DOM manipulations

In jQuery, you design a page, and then you make it dynamic. This is because jQuery was designed for augmentation and has grown incredibly from that simple premise.

But in AngularJS, you must start from the ground up with your architecture in mind. Instead of starting by thinking "I have this piece of the DOM and I want to make it do X", you have to start with what you want to accomplish, then go about designing your application, and then finally go about designing your view.

2. Don't augment jQuery with AngularJS

Similarly, don't start with the idea that jQuery does X, Y, and Z, so I'll just add AngularJS on top of that for models and controllers. This is really tempting when you're just starting out, which is why I always recommend that new AngularJS developers don't use jQuery at all, at least until they get used to doing things the "Angular Way".

I've seen many developers here and on the mailing list create these elaborate solutions with jQuery plugins of 150 or 200 lines of code that they then glue into AngularJS with a collection of callbacks and $applys that are confusing and convoluted; but they eventually get it working! The problem is that in most cases that jQuery plugin could be rewritten in AngularJS in a fraction of the code, where suddenly everything becomes comprehensible and straightforward.

The bottom line is this: when solutioning, first "think in AngularJS"; if you can't think of a solution, ask the community; if after all of that there is no easy solution, then feel free to reach for the jQuery. But don't let jQuery become a crutch or you'll never master AngularJS.

3. Always think in terms of architecture

First know that single-page applications are applications. They're not webpages. So we need to think like a server-side developer in addition to thinking like a client-side developer. We have to think about how to divide our application into individual, extensible, testable components.

So then how do you do that? How do you "think in AngularJS"? Here are some general principles, contrasted with jQuery.

The view is the "official record"

In jQuery, we programmatically change the view. We could have a dropdown menu defined as a ul like so:

<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>

In jQuery, in our application logic, we would activate it with something like:

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

When we just look at the view, it's not immediately obvious that there is any functionality here. For small applications, that's fine. But for non-trivial applications, things quickly get confusing and hard to maintain.

In AngularJS, though, the view is the official record of view-based functionality. Our ul declaration would look like this instead:

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

These two do the same thing, but in the AngularJS version anyone looking at the template knows what's supposed to happen. Whenever a new member of the development team comes on board, she can look at this and then know that there is a directive called dropdownMenu operating on it; she doesn't need to intuit the right answer or sift through any code. The view told us what was supposed to happen. Much cleaner.

Developers new to AngularJS often ask a question like: how do I find all links of a specific kind and add a directive onto them. The developer is always flabbergasted when we reply: you don't. But the reason you don't do that is that this is like half-jQuery, half-AngularJS, and no good. The problem here is that the developer is trying to "do jQuery" in the context of AngularJS. That's never going to work well. The view is the official record. Outside of a directive (more on this below), you never, ever, never change the DOM. And directives are applied in the view, so intent is clear.

Remember: don't design, and then mark up. You must architect, and then design.

Data binding

This is by far one of the most awesome features of AngularJS and cuts out a lot of the need to do the kinds of DOM manipulations I mentioned in the previous section. AngularJS will automatically update your view so you don't have to! In jQuery, we respond to events and then update content. Something like:

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

For a view that looks like this:

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

Apart from mixing concerns, we also have the same problems of signifying intent that I mentioned before. But more importantly, we had to manually reference and update a DOM node. And if we want to delete a log entry, we have to code against the DOM for that too. How do we test the logic apart from the DOM? And what if we want to change the presentation?

This a little messy and a trifle frail. But in AngularJS, we can do this:

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

And our view can look like this:

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

But for that matter, our view could look like this:

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

And now instead of using an unordered list, we're using Bootstrap alert boxes. And we never had to change the controller code! But more importantly, no matter where or how the log gets updated, the view will change too. Automatically. Neat!

Though I didn't show it here, the data binding is two-way. So those log messages could also be editable in the view just by doing this: <input ng-model="entry.msg" />. And there was much rejoicing.

Distinct model layer

In jQuery, the DOM is kind of like the model. But in AngularJS, we have a separate model layer that we can manage in any way we want, completely independently from the view. This helps for the above data binding, maintains separation of concerns, and introduces far greater testability. Other answers mentioned this point, so I'll just leave it at that.

Separation of concerns

And all of the above tie into this over-arching theme: keep your concerns separate. Your view acts as the official record of what is supposed to happen (for the most part); your model represents your data; you have a service layer to perform reusable tasks; you do DOM manipulation and augment your view with directives; and you glue it all together with controllers. This was also mentioned in other answers, and the only thing I would add pertains to testability, which I discuss in another section below.

Dependency injection

To help us out with separation of concerns is dependency injection (DI). If you come from a server-side language (from Java to PHP) you're probably familiar with this concept already, but if you're a client-side guy coming from jQuery, this concept can seem anything from silly to superfluous to hipster. But it's not. :-)

From a broad perspective, DI means that you can declare components very freely and then from any other component, just ask for an instance of it and it will be granted. You don't have to know about loading order, or file locations, or anything like that. The power may not immediately be visible, but I'll provide just one (common) example: testing.

Let's say in our application, we require a service that implements server-side storage through a REST API and, depending on application state, local storage as well. When running tests on our controllers, we don't want to have to communicate with the server - we're testing the controller, after all. We can just add a mock service of the same name as our original component, and the injector will ensure that our controller gets the fake one automatically - our controller doesn't and needn't know the difference.

Speaking of testing...

4. Test-driven development - always

This is really part of section 3 on architecture, but it's so important that I'm putting it as its own top-level section.

Out of all of the many jQuery plugins you've seen, used, or written, how many of them had an accompanying test suite? Not very many because jQuery isn't very amenable to that. But AngularJS is.

In jQuery, the only way to test is often to create the component independently with a sample/demo page against which our tests can perform DOM manipulation. So then we have to develop a component separately and then integrate it into our application. How inconvenient! So much of the time, when developing with jQuery, we opt for iterative instead of test-driven development. And who could blame us?

But because we have separation of concerns, we can do test-driven development iteratively in AngularJS! For example, let's say we want a super-simple directive to indicate in our menu what our current route is. We can declare what we want in the view of our application:

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

Okay, now we can write a test 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 when we run our test, we can confirm that it fails. Only now should we create 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 test now passes and our menu performs as requested. Our development is both iterative and test-driven. Wicked-cool.

5. Conceptually, directives are not packaged jQuery

You'll often hear "only do DOM manipulation in a directive". This is a necessity. Treat it with due deference!

But let's dive a little deeper...

Some directives just decorate what's already in the view (think ngClass) and therefore sometimes do DOM manipulation straight away and then are basically done. But if a directive is like a "widget" and has a template, it should also respect separation of concerns. That is, the template too should remain largely independent from its implementation in the link and controller functions.

AngularJS comes with an entire set of tools to make this very easy; with ngClass we can dynamically update the class; ngModel allows two-way data binding; ngShow and ngHide programmatically show or hide an element; and many more - including the ones we write ourselves. In other words, we can do all kinds of awesomeness without DOM manipulation. The less DOM manipulation, the easier directives are to test, the easier they are to style, the easier they are to change in the future, and the more re-usable and distributable they are.

I see lots of developers new to AngularJS using directives as the place to throw a bunch of jQuery. In other words, they think "since I can't do DOM manipulation in the controller, I'll take that code put it in a directive". While that certainly is much better, it's often still wrong.

Think of the logger we programmed in section 3. Even if we put that in a directive, we still want to do it the "Angular Way". It still doesn't take any DOM manipulation! There are lots of times when DOM manipulation is necessary, but it's a lot rarer than you think! Before doing DOM manipulation anywhere in your application, ask yourself if you really need to. There might be a better way.

Here's a quick example that shows the pattern I see most frequently. We want a toggleable button. (Note: this example is a little contrived and a skosh verbose to represent more complicated cases that are solved in exactly the same way.)

.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);
            });
        }
    };
});

There are a few things wrong with this:

  1. First, jQuery was never necessary. There's nothing we did here that needed jQuery at all!
  2. Second, even if we already have jQuery on our page, there's no reason to use it here; we can simply use angular.element and our component will still work when dropped into a project that doesn't have jQuery.
  3. Third, even assuming jQuery was required for this directive to work, jqLite (angular.element) will always use jQuery if it was loaded! So we needn't use the $ - we can just use angular.element.
  4. Fourth, closely related to the third, is that jqLite elements needn't be wrapped in $ - the element that is passed to the link function would already be a jQuery element!
  5. And fifth, which we've mentioned in previous sections, why are we mixing template stuff into our logic?

This directive can be rewritten (even for very complicated cases!) much more simply like so:

.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;
            };
        }
    };
});

Again, the template stuff is in the template, so you (or your users) can easily swap it out for one that meets any style necessary, and the logic never had to be touched. Reusability - boom!

And there are still all those other benefits, like testing - it's easy! No matter what's in the template, the directive's internal API is never touched, so refactoring is easy. You can change the template as much as you want without touching the directive. And no matter what you change, your tests still pass.

w00t!

So if directives aren't just collections of jQuery-like functions, what are they? Directives are actually extensions of HTML. If HTML doesn't do something you need it to do, you write a directive to do it for you, and then use it just as if it was part of HTML.

Put another way, if AngularJS doesn't do something out of the box, think how the team would accomplish it to fit right in with ngClick, ngClass, et al.

Summary

Don't even use jQuery. Don't even include it. It will hold you back. And when you come to a problem that you think you know how to solve in jQuery already, before you reach for the $, try to think about how to do it within the confines the AngularJS. If you don't know, ask! 19 times out of 20, the best way to do it doesn't need jQuery and to try to solve it with jQuery results in more work for you.

这篇关于“Thinking in AngularJS”如果我有一个jQuery的背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆