Toggle navigation ng-book. Looking for ng-book 2? Jump to packages. Stop wasting your time wrestling with incomplete and confusing tutorials Piecing together the docs is tough The documentation is not self-explanatory, one tutorial says one thing and another says something completely different. Googling only takes you so far There are not many good screencasts or tutorials out there that teach how to maximize the framework. Some teach the basics, but nothing that shows how to fit everything together?
Time is money; don't waste it sifting through blogs. Not only does it take a few trips around the community to have a basic understanding, but it's tough to find the answer you need. The vocabulary is foreign, when are you supposed to use a directive, a filter, or a factory? How does it all fit together? The internals of AngularJS 1. How do you know how it all fits together?
Still not hitting deadlines faster. What if you could master the entire framework — with solid foundations — in less time without beating your head against a wall? Imagine how quickly you could work if you knew the best practices and the best tools? Stop wasting your time searching and have everything you need to be productive in one, well-organized place, with complete examples to get your project up without needing to resort to endless hours of research.
Get up and running quickly Within the first few minutes, you'll know enough Angular concepts to start writing your modern webapp. Comprehensive topics You'll learn core Angular concepts - from how Angular works under the hood to rich animations, from in-depth testing to real-world applications.
Best practices Learn AngularJS best practices , such as testing, code organization, and how to structure your app for performance. Up to date The book is constantly updated with the latest tips and tricks of Angular.
What's in it? How to use AngularJS to your advantage How to build and use controllers and work with scopes How to build views, templates, and best practices You'll learn to master the core directives and build your own custom directives You'll learn how to implement real-world authentication How to test all parts of your applications You'll know exactly how Angular works, from bootstrapping to garbage collection.
You'll communicate with back-end services of your choosing. What the community says Imagine how quickly you could work if you knew the best practices an ng-book. Imagine how quickly you could work if you knew the best practices and the best tools? Stop wasting your time searching and have everything you need to be productive in one, well-organized place, with complete examples to get your project up without needing to resort to endless hours of research.
You will learn what you need to know to work professionally with ng-book: The Complete Book on Angular. Get up and running quickly The first chapter opens with building your first Angular app.
Within the first few minutes, you'll know enough to have an app running Lots of Sample Apps and Code When you buy ng-book, you're not buying just a book, but dozens of code examples. Every chapter in the book comes with a complete project that uses the concepts in the chapter. The code is available for download, free from our website. We'll walk through practical, common examples of how to implement complete components of your applications Example Apps included in the book The book comes with sample apps that show you how to create: A component-based Reddit clone A real-time chat app using RxJS Observables A YouTube search-as-you-type app A Spotify search for tracks with playable song preview Plus lots more mini-examples that show you how to write Components, how to use Forms, and how to use APIs The code examples currently have over 5,] lines of runnable code TypeScript, non-comment lines What our Customers Say "Fantastic work guys!
I have no idea where I'd be with Angular without ng-book. Thanks again.. I think it is the best learning material one can find about Angular today.
This revision of the book covers up to angular An updated version of the code is available for free at our website. Do I have to know Angular 1? We don't assume that you've used Angular 1. This book teaches Angular from the ground up. Of course, if you've used Angular 1, we'll point out common ideas because there are many , but ng-book stands on its own Is ng-book an upgrade to ng-book 1? This is a completely new book and shares no content or code with ng-book 1. Get A Copy. Paperback , pages.
More Details Other Editions 1. Friend Reviews. To see what your friends thought of this book, please sign up. To ask other readers questions about Ng-Book , please sign up.
Lists with This Book. This book is not yet featured on Listopia. Add this book to your favorite list ». Chuck full of clear instructions and complete examples, this book's goal is to demystify Angular. It's a great grab for beginners! A great buy for intermediate-level web developers that are already comfortable with modern web frameworks and libraries. Sweeping a wide circle, this book tackles the entire elephant. It was written by a Google Developer expert and won a super review from Stephen Fluin see below.
Doguhan uses the latest and greatest best practices around command line tooling like npx, with great Angular techniques like lazy loading. Doguhan's work brings together thousands of little best practices that he has learned in his time working with developers, and from his own experience into one book. The book shows lots of realistic code examples, that are all runnable and available from the author's GitHub repositories. If you want to understand how to write solid Angular applications in , then you must read this book.
Advertised as the one-stop-shop for learning Angular and claiming to be the most comprehensive book on Angular available. If you're a beginner that wants one book then this is yours. After sooo many years of writing books Adam's style just gets better and better with every new edition. I read other books by Adam Freeman and he always delivers. Highly recommend. Yes I could use it and copy-cat great working solutions, but the real understanding came when I worked through all the excellent examples in this book.
By now I created 2 SportsStores by following the excellent build up of the examples in the books. I can highly recommend Adam's books. With an aim to make you a testing pro, this Angular book is all about squishing the bugs out of your application. We can specify one or many formats. Technically, we can fix that by declaring new tags in the head of our document see Angular with IE , but doing so can cause us headaches in the future if we neglect to be consistent.
A noteworthy exception is when extending built-in HTML tags. We can even create a new child scope when building a custom directive of our own. We can provide a nicer experience for others using our directive if we specify the URL and link text without messing with the internal guts of the directive.
Our goal here is to pay attention to the public interface of our directive, just as we would in any programming language. Updating template To set properties on the inner scope of our directive, we have a few options. While simple, however, sharing state leaves us vulnerable. To overcome this common issue, Angular provides the ability to create a new child scope or create an isolate scope. In contrast to inherited scope child scope , discussed earlier in current scope intro- duction , an isolate scope is completely separate from the current scope of the DOM.
Chrome Developer tool This behavior occurs because the built-in directive, ng-model, is set up with a two-way binding between its own isolate scope and the scope of the DOM provided by a controller. Our goal is to understand two-way bindings and the behavior of ng-model in the process. To understand the magic, however, we need to implement it ourselves. See binding strategies explained. In summary, this example explains the magic of one of the fundamental selling points of Angular, two-way data binding.
Built-In Directives Angular provides a suite of built-in directives. When we use tags in our HTML, it may not be immediately obvious that we are, in fact, using a directive. Other built-in directives are clearly visible via their ng- namespace prefix.
Lastly, some built-in directives do not have an HTML counterpart, such as the ng-controller directive, which can be used as an attribute on any tag, but is most often found on an element that has many children that should share the same scope.
Note that all directives prefixed with the ng namespace are part of the built-in library of directives that ship with Angular. For this reason, never prefix directives you make with this namespace. If absent, the attribute is assumed to be false.
When working with dynamic data via data bindings in Angular, we cannot simply set the value of the attribute to true or false, because by definition of the spec, the attribute is false if it is not present. Thus Angular provides an ng-prefixed version of these attributes that will evaluate the expression provided to insert or remove the corresponding boolean attribute on the decorated element.
To bind the presence or not of this attribute, use ng-disabled. In order for Angular to bind the presence of the checked attribute to the value of an expression, use ng-checked. In the following example, we set the value of someProperty to true using the ng-init directive. Binding the value of someProperty to ng-checked then tells Angular to output the standard HTML checked attribute, which will check the box by default. Both ng-href and ng-src are so likely to help improve refactoring and prevent errors when changing code later in a project that it is recommended to use them in place of href and src, respectively.
The issue here is that the user is able to click a link built with href before interpolation takes place, which would bring them to the wrong page often a Notice that one request is red, indicating that there was an error. Directives with Child Scope The following directives create a child scope that prototypically inherits from its parent. This inheritance provides a layer of separation meant for storing methods and model objects that work together to achieve a common goal.
We can only use ng-app once per document. We will talk more about manually bootstrapping apps in the under the hood chapter.
Persistent state should be bound to a service, which is then responsible for dealing with persisting that model. Data in the DOM should always use a. Following this rule will keep you out of unexpected trouble. Controllers should be as simple as possible. See application architecture for more information. To see this problem in action, try clicking on the child button first and then the parent button. Doing so makes it clear that the child controller has copy, not a reference to someBareValue.
JavaScript objects are either copy by value or copy by reference. String, Number, and Boolean are copy by value.
Array, Object, and Function are copy by reference. Had we set our string as a property on a model object, it would have been shared via reference, which means changing the property on the child will change it on the parent. The value always remains in sync. Note that while this behavior manifests itself most noticeably when using ng-controller, it will also rear its ugly head when using any directive that creates a new child scope by setting the scope property inside its directive definition to true.
The URL of the template is restricted to the same domain and protocol as the application document unless whitelisted or wrapped as trusted values. While developing, you may run Chrome from the command line with chrome --allow-file-access-from-files to disable the CORS error. Only go this route in an emergency e. Keep in mind that when using ng-include, Angular automatically creates a new child scope. In the following example, when person. We will cover this in depth in the routing chapter.
See the routing chapter for more information. If the expression assigned to ng-if evaluates to a false value, then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM. When an element is removed from the DOM using ng-if, its associated scope is destroyed. Furthermore, when it comes back into being, a new scope is created and inherits from its parent scope using prototypal inheritance.
If code inside of ng-if is loaded, is manipulated using jQuery for example, using. Each item in the collection is given its own template and therefore its own scope. Remember that in JavaScript arrays are indexed starting at 0; thus, we use! The most common use case for using ng-init is when creating small examples for educational purposes, like the examples in this chapter. For anything substantial, create a controller and set up state within a model object. To prevent this issue, use ng-bind instead.
We can prevent this FOUC from being exposed by using ng-bind and binding our content to the element. The content will then render as the child text node of the element on which ng-bind is declared. It handles and provides validation, sets related CSS classes on the element ng-valid, ng-invalid, etc. It binds to the property given by evaluating the expression on the current scope.
Setting ng-model as a property of the scope will help us avoid overloading properties on the same scope or the inherited scope. The bottom line is to always have a. For in-depth discussion and an example on this topic, see the ng-controller section earlier in this chapter.
When the expression provided to the ng-show attribute is false the element is hidden. Similarly, when the expression given to ng-hide is true, the element is hidden.
The element is shown or hidden by removing the ng-hide CSS class from, or adding it to, the element. That means that the outer form is valid when all of the child forms are valid, as well. This fact is especially useful when dynamically generating forms using ng-repeat. Because we cannot dynamically generate the name attribute of input elements using interpolation, we need to wrap each set of repeated inputs in an ng-form directive and nest these in an outer form element. In the following examples, we want to dynamically generate a form based on a JSON response from the server.
Because Angular forms that use ng-form instead of form can be nested, and because the parent form is not valid until its child forms are valid, we can both dynamically generate a form with child forms and use validation. Yes, we can have our cake and eat it too. This directive can be used in conjunction with ng-model and ng-options to provide sophisticated and highly performant dynamic forms.
This directive also prevents the default action sending the request and reloading the page , but only if the form does not contain an action attribute. Duplicate classes will not be added. When the expression changes, the previously added classes are removed and only then are the new classes added. To fix this problem, we can use ng-attr-cx. Notice that the cx is named after the attribute we would like to define.
Directive Definition The simplest way to think about a directive is that it is simply a function that we run on a particular DOM element. The function is expected to provide extra functionality on the element.
For instance, the ng-click directive gives an element the ability to listen for the click event and run an Angular expression when it receives the event. A directive is defined using the. Directives Explained angular. When a function is returned, it is often referred to as the postLink function, which allows us to define the link function for the directive.
Returning a function instead of an object limits us to a narrow ability to customize our directive and, thus, is good for only simple directives. When Angular bootstraps our app, it will register the returned object by the name provided as a string via the first argument. The Angular compiler parses the DOM of our main HTML document looking for elements, attributes, comments, or class names using that name when looking for these directives. When it finds one that it knows about, it uses the directive definition to place the DOM element on the page.
Angular itself has chosen the ng- prefix, so use something other than that. The factory function we define for a directive is only invoked once, when the compiler matches the directive the first time. Just like the. A JavaScript object is made up of keys and values. When the value for a given key is set to a string, boolean, number, array, or object, we call the key a property. When we set the key to a function, we call it a method. The possible options are shown below.
It is responsible for telling Angular in which format our directive will be declared in the DOM. By default, Angular expects that we will declare a custom directive as an attribute, meaning the restrict option is set to A. See the chapter on Internet Explorer for more information on this topic. Avoid using comments to declare a directive. This format was originally introduced as a way to create directives that span multiple elements. If you are curious, however, take a look at the Chrome developer tools elements tab when using ng-repeat to see comments being used under the hood.
Element or Attribute? Use an element when creating something new on the page that will encapsulate a self-contained piece of functionality. Use an attribute when decorating an existing element with data or behavior. The guiding principle here is that the format of a directive tells a story about our applications and reveals the intent of each piece, creating exemplary code that is easy to understand and share with others.
The other distinction that is important to make for a given directive is whether it creates, inherits, or isolates itself from the scope of its containing environment. Priority number The priority option can be set to a number. For example, ngRepeat sets this option at so that it always gets invoked before other directives on the same element.
If an element is decorated with two directives that have the same priority, then the first directive declared on the element will be invoked first. It is always invoked before other directives on the same element. Performance is a key factor here.
Terminal boolean terminal is a boolean option; it can be set to true or false. We use the terminal option to tell Angular to stop invoking any further directives on an element that have a higher priority. All directives with the same priority will be executed, however. Directives Explained Template string function template is optional.
The t in tElement and tAttrs stands for template, as opposed to instance. Angular treats the template string no differently than any other HTML. When a template string contains more than one DOM element or only a single text node, it must be wrapped in a parent element. We include these so that Angular can parse multi-line strings correctly. In production code, it would be a better choice to use the templateUrl option because multi-lines strings are a nightmare to look at and maintain.
One of the most important features to understand about a template string or templateURL is how it gets its scope. The function must return the path to an HTML file as a string. Having to wait for a large number of templates to asynchronously load via Ajax can really slow down a client-side application. Caching is a better option in most cases because Angular will not make an Ajax request, thus providing better performance by minimizing the number of requests run.
For more information about caching, check out the in-depth discussion on caching here. For more information about how this adjustment works, see the next steps chapter.
If provided, it must be set to true. It is set to false by default. Furthermore, inside this second div is another div that also has get and set access to the exact same root scope. Just because a directive is nested within another directive does not necessarily mean its scope has been changed.
By default, child directives are given access to the exact same scope as their parent DOM nodes. The reason for that can be understood by learning about the scope directive option, which is set to false by default. Directives Explained Scope Option boolean object scope is optional. By default, it is set to false. When scope is set to true, a new scope object is created that prototypically inherits from its parent scope.
If multiple directives on an element provide an isolate scope, only one new scope is applied. Root elements within the template of a directive always get a new scope; thus, for those objects, scope is set to true by default. The built-in ng-controller directive exists for the sole purpose of creating a new child scope that prototypically inherits from the surrounding scope.
It creates a new scope that inherits from the surrounding scope. Inside the third div, however, the value we set inside our inherited scope data for a 3rd property is shown. Isolate Scope Isolate scope is likely the most confusing of the three options available when setting the scope property, but also the most powerful.
Isolate scope is based on the ideology present in Object Oriented Programming. Two-Way Data Binding Perhaps the most powerful feature in Angular, two-way data binding allows us to bind the value of a property inside the private scope of our directive to the value of an attribute available within the DOM.
In the previous chapter on directives we looked at a good example of how ng-model provides two-way data binding with the outside world and a custom directive we created; this example in many ways mirrored the behavior that ng-bind, itself, provides. Review that chapter and practice the example to gain a greater understanding of this important concept.
Transclude transclude is optional. Transclusion is most often used for creating reusable widgets. A great example is a modal box or a navbar. Transclude allows us to pass in an entire template, including its scope, to a directive.
Doing so gives us the opportunity to pass in arbitrary content and arbitrary scope to a directive. If the scope option is not set, then the scope available inside the directive will be applied to the template passed in.
Only use transclude: true when you want to create a directive that wraps arbitrary content. Transclusion makes it easy to allow users of our directive to customize all these aspects at once by allowing them to provide their own HTML template that has its own state and behavior. We can reuse this directive with the transclusion to provide a secondary element without needing to worry about the styles and the layout.
Directives Explained Controller string function The controller option takes a string or a function. When set to a string, the name of the string is used to look up a controller constructor function registered elsewhere in our application: angular.
This transclude linking function is the function that will run to actually create a clone of the element and manipulate the DOM. It goes against the Angular Way to manipulate the DOM inside of a controller, but it is possible through the linking function.
It is a best practice to only use this transcludeFn inside the compile option. The main use case for a controller is when we want to provide reusable behavior between directives. As the link function is only available inside the current directive, any behavior defined within is not shareable.
Directives Explained The link function provides isolation between directives, while the controller defines shareable behavior. Because a directive can require the controller of another directive, however, controllers are a great place to place actions we may want to use in more than one directive. Using the controller option is good when we want to expose an API to other directives; otherwise, we can rely on link to provide us local functionality for the directive element.
Use the scope argument passed into the link function when expecting to interact with the instance of the scope on screen. ControllerAs string The controllerAs option enables us to set a controller alias, thus allowing us to publish our controller under this name and giving the scope access to the controllerAs name. That power allows us to create dynamic objects as controllers that are isolated and easy to test.
For instance, we can create an anonymous controller in a directive, like so: angular. The string s contain the name of another directive. The string or strings if it is an array provided are the names of directives that reside in the current scope of the current directive.
The scope setting will affect what the surrounding scope refers to, be it an isolate scope, an independent scope, or no scope at all. In all cases, the Angular compiler will consult the template of the current directive when looking for child controllers. If the required controller is not found on the directive provided, pass null to the 4th argument of the link function. Technically, we need to have a controller associated with anything we put in the require option. How does this magic take place, and what do we need to know in order to build effective applications?
There are two main phases that take place. Directives Explained Compile Phase The first is called the compile phase. Each directive can have a template that may contain directives, which may have their own templates. When Angular invokes a directive in the root HTML document, it will traverse the template for that directive, which itself may contain directives, each with its own template.
This tree of templates can go arbitrarily deep and wide, but there is one caveat. The practical advice here is to separate directives that contain templates from those that add behavior. Never further decorate an element with another directive if that element already has a directive that brings its own template. Only the template of the directive with the highest priority will have its template compiled.
Once a directive and its child templates have been walked or compiled, a function is returned for the compiled template known as the template function. Before the template function for a directive is returned, however, we have the opportunity to modify the compiled DOM tree. During this phase, built-in directives, such as ng-repeat and ng-transclude, take advantage of this fact and manipulate the DOM before it has been bound to any scope data.
Once we have compiled a complete representation of a single directive, we momentarily have access to it via the compile function, whose method signature includes access to the element where the directive was declared tElement and other attributes provided to that element tAttrs. This compile function returns the template function mentioned above , which includes the entire parsed tree. The main takeaway here is that because each directive may have its own template and its own compile function, each directive returns its own template function.
Finally, the template function is passed to the link function, where scope, determined by the directive definition rules of each directive in the compiled DOM tree, is applied all at once.
This compile then link process provides our applications with huge performance gains. Compile object function The compile option can return an object or a function. The compile option by itself is not explicitly used very often; however, the link function is used very often. Here, it is safe to manipulate HTML, add and remove elements, etc.
The compile option and the link option are mutually exclusive. If both are set, then the compile option will be expected to return the link function, while the link option will simply be ignored. The template instance and link instance may be different objects if the template has been cloned. The link function deals with linking scope to the DOM.
In practice, this manipulation is rather rare when writing custom directives, but there are a few built-in directives that take advantage of this functionality. Understanding the process will help us understand how Angular actually works.
Link We use the link option to create a directive that manipulates the DOM. The link function is optional. If the compile function is defined, it returns the link function; therefore, the compile function will overwrite the link function when both are defined. When doing so, this function will be the link function.
These two definitions of the directive are functionally equal: angular. In essence, this fact describes precisely what the link function is responsible for. It is invoked after the compiled template has been linked to the scope, and is therefore responsible for setting up event listeners, watching for data changes, and manipulating the live DOM.
The link function has control over the live data-bound DOM, and, as such, performance con- siderations should be taken into account. Review the section on the life cycle of a directive for more information on performance concerns when choosing to implement something in the compile function versus the link function.
We should only manipulate children of this element in the postLink function, since the children have already been linked. These are passed as JavaScript objects. If there is no require option defined, then this controller argument is set as undefined. The controller is shared among all directives, which allows the directives to use the controllers as a communication channel public API.
If multiple requires are set, then this will be an array of controller instances, rather than just a single controller. The ngModel controller, which is injected along with ngModel when we use it in our directive, contains several methods.
Notice that this directive does not have an isolated scope. If we do set the directive to have the isolate scope, then the ngModel value will not update the outer ngModel value: Angular looks up this value outside of the local scope.
In order to set the view value of a scope, we must call the API function ngModel. We should apply this method only sparingly, as it can be disruptive to the Angular Way: angular. These are used to sanitize and modify the value. We have described how the validation pipeline works, at a basic level. These functions do not need to return a value, as they are ignored.
It will be true if there are no errors and false if there are. Angular Module Loading Angular modules, themselves, have the opportunity to configure themselves before the module actually bootstraps and starts to run.
We can apply different sets of logic during the bootstrap phase of the app. Configuration Angular executes blocks of configuration during the provider registration and configuration phases in the bootstrapping of the module. This phase is the only part of the Angular flow that may be modified before the app starts up.
For instance, when we create a factory or a directive on top of the module: angular. That is to say that we cannot inject a provider that has not yet been defined. The only exception to the rule of in-order definitions is the constant method.
We always place these at the beginning of all configuration blocks. If we inject any old service into a. The by-product of this strict requirement for configurable services is that we can only inject custom services that are built with the provider syntax and cannot inject other services. For more information on how to build with the provider syntax, head over to the services chapter.
We can also define multiple configuration blocks, which are executed in order and allow us to focus our configuration in the different phases of the app. Angular Module Loading angular. Run Blocks Unlike the configuration blocks, run blocks are executed after the injector is created and are the first methods that are executed in any Angular app. Run blocks are the closest thing in Angular to the main method. The run block is code that is typically hard to unit test and is related to the general app.
The only logical place to set this functionality is in the run method: angular. Multiple Views and Routing In a single-page app, navigating from one page view to another is crucial. When apps grow more and more complex, we need a way to manage the screens that a user will see as they navigate their way through the app.
0コメント