Site icon Codemotion

AngularJS for accustomed to jQuery

Angularjs – perfect framework for building web applications. He has great documentation provided with examples. In teaching “test” applications (such TodoMVC Project ), he is very worthy shows itself from the rest of other frameworks. According to him there are excellent presentations and screencasts.

However, if the developer had never encountered frameworks, like Angular, and used to work mostly like the jQuery library, then it can be difficult to change your way of thinking. At least, so it was with me, and I would like to share some notes on the subject. Perhaps someone it will be useful.

Not library

The first thing to understand about Angular: it is a completely different instrument. jQuery – a library. AngularJS – this framework. When your code works with the library, he decides when to call this or that function. In the case of framework you implement the event handlers, and have a framework to decide at what point they cause.

This difference is easier to understand if you think about what is happening during the performance. What jQuery does in runtime? Almost nothing. jQuery code is called only in response to something that happened in your code – when load trigger any of the functions caused by DOM event.

Angular is the download stage turns your DOM tree and angular-code in an application. HTML-page layout with angular-directives and filters it compiled in the template tree corresponding scope (scope) and controllers join them in the right places, internal applications work cycle provides the correct data binding between presentation and model. This is really a working arrangement in full accordance with the principles of MVC, which ensures a very clean separation between the presentation, the controller and the model. If we talk about the overall event loop, rendering pages and data binding, you can assume that it is carried out continuously at all times, causing the code of your controllers only when required.

Each model is updated (either through asynchronous AJAX-request or directly through the change of data from the controller) Angular restarts the cycle $ special procedure the digest, which updates the data binding, and retains all the up to date system.

Declarative approach rather than mandatory

Unlike some other libraries and frameworks, Angular not HTML as regards the problem, you want to solve (I will not point fingers). Instead, it extends them so naturally that inevitably wondered why he had not previously thought of. It is easier to show than to explain.

Suppose we want to show and hide an element, based on the state of the checkbox. In jQuery, we would do it something like:

<input id="toggleShowHide" type="checkbox">
<div id=”specialParagraph”>
    This content will disappear and reappear if you click the checkbox above
</div>

[divider type=”linebreak”]

$(function() {
     function toggle() {
        var isChecked = $('#toggleShowHide).is(':checked');
        var specialParagraph = $('#specialParagraph');
        if (isChecked) {
            specialParagraph.show();
        } else {
            specialParagraph.hide();
        }
    }
    $('#toggleShowHide).change(function() {
        toggle();
    });
    toggle();
});

Note that the javascript code-DOM here perceives in terms of the imperative approach: take this element and its attribute, look at the value, do so-and-so.

Now look at the same thing in terms of Angular:

<input ng-model="showSpecial" type="checkbox">
<div ng-show=”showSpecial”>
    This content will disappear and reappear if you click the checkbox above
</div>

And yet! Code is not at all, just pure determination declarative style bindings and rules. Here is a demonstration of this code in jsFiddle: jsfiddle.net/Y2M3r

Direct manipulation of the DOM is not simply cease to be binding; we can say even more, their use Angular approach is not recommended. The DOM tree to be fully defined in the templates, data – in the models and areas of visibility, functionality – in controllers, any custom transformation – in their own filters and directives.

This clear division of tasks at first glance looks indigestible, but as the project grows, it will pay off handsomely: the code is easy to maintain, it is easy to divide into modules, is convenient to test and explore.

Two-way data binding

The process of tying the value of the DOM data model through the controller and its field of view creates the most that neither is “binding” in the full sense of the word. Most likely, you already know this from the documentation and examples, but I just can not say it is not. This is one of the most powerful first impressions of use Angular.

<input type="text" ng-model="yourName" placeholder="Your name" />
<h1>Hello {{yourName}}!</h1>

Demonstration: jsfiddle.net/6UnVA/1

Implementation depending

I speak for a few cocky, but Angular implemented the most elegant way to track dependencies in the world.

Assume you have some source of JSON-data, wrapped in a special service $ resource on the side of Angular.

DataSource = $resource(url, default_params, method_details)

(Refer to the documentation for more details)

Any function controller, which requires that data can enable DataSource to your list of options. This is all that is required of it. It’s a small street magic that never ceases to amaze me every day when working with AngularJS. You need to perform asynchronous HTTP-requests from the controller? Add $ in http settings. We need to write to the console log? Add $ log as an argument to your function.

Inside, at this point, the following occurs: Angular analyzes source code funtsktsii, is a list of arguments and concludes, what services are required to your code.

Data access

In addition, Angular that gives you complete freedom of choice in how to organize the data in the model (you can use simple variables, objects and arrays in any combination), it also provides a convenient way to communicate with a REST API on the server. For example, we want to receive and keep a record of users. Here’s how to access them can be arranged:

var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

Angular has a good presets for common sampling operations, delete, retrieve, and modify data. A spetsparametry in the URL gives the ability to customize the access to suit your needs.

Other important points are left out – it is, for example, form validation, unit testing (not just unit testing, I personally think is even more important than a lot of the article – approx lane..) And a library angular-ui. Perhaps in future posts.

Exit mobile version