Ng book angular 6 pdf download
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.
We can already support such management by including template code in line in the main HTML, but not only will this in-line code grow large and unmanageable, it will also make it difficult to allow other developers to join in development. Rather than including multiple templates in the view which we could do with the ng-include directive , we can break out the view into a layout and template views and only show the view we want to show based upon the URL the user is currently accessing.
Installation As of version 1. In order to use routes in our Angular app, we need to install and reference it in our app. We can download it from code. We can also install it using Bower, which will place it in our usual Bower directory. For more information about Bower, see the Bower chapter. Using the ng-view directive in combination with the router, we can specify exactly where in the DOM we want to place the rendered template of the current route.
It creates its own scope and nests the template inside of it. The ng-view directive is a terminal directive at a priority. Angular will not run any directives on the element at a lower priority, which is most directives i. To create a route on a specific module or app, we use the config function. For more information on this syntax, check out the dependency injection chapter.
Now, to add a specific route, we can use the when method. This method takes two parameters when path, route. This block shows how can create a single route: angular.
Trailing or double slashes will still work. We can store parameters in the URL by starting off the name with a colon for instance, :name. The second parameter is the configuration object, which determines exactly what to do if the route in the first parameter is matched. The configuration object properties that we can set are controller, template, templateURL, resolve, redirectTo, and reloadOnSearch. A more complex routing scenario requires multiple routes and a catch-all that redirects a route.
Multiple Views and Routing angular. If we pass a string, it associates the registered controller on the module with the new route. If we pass a function, this function will be associated with the template as the controller for the DOM element. The data key of the map above will be injected into our controller, so it can be retrieved in the controller. If the redirectTo property is set with a function, the result of the function will be set as the value of the new path, triggering a route-change request.
This tip is useful for nested routing or in-place pagination, etc. Now we can set up our routes using the when function. If no route matches, then the otherwise method will be called. When the browser loads the Angular app, it will default to the URL set as the default route. It also gives you the ability to change paths and deal with any sort of navigation. Doing so returns the location object. A hash object might contain an array of values as well. If the value is null, then the parameter will be removed.
The routing mode determines what the URL of your site will look like. In hashbang mode the fallback for html5 mode , URL paths take a prepended character. This prefix is part of the fallback mechanism that Angular uses for older browsers. We can also configure this character. To configure the hashPrefix: angular. In a modern browser, it will see the URL as it was intended. The back-end server will have to support URL rewriting on the server side.
To support HTML5 mode, the server will have to make sure to deliver the index. That ensures that our Angular app will handle the route. This functionality is useful particularly when you want to manipulate events based upon routes and is particularly useful for detecting when users are logged in and authenticated.
We need to set up an event listener to listen for routing events. This step is where the route services begin to resolve all of the dependencies necessary for the route change to happen and where templates and the resolve keys are resolved. Note About Indexing Web crawlers traditionally have a hard time with fat client-side JavaScript apps. To support web crawlers that run through the app, we need to add a meta tag in the head. This meta tag causes the crawler to request links with an empty escaped fragment parameter so that the back end will serve back snippets of HTML.
Dependency Injection In general, there are only three ways an object can get a hold of its dependencies: 1. We can create it internally to the dependent. We can look it up or refer to it as a global variable. Dependency injection is a design pattern that allows for the removal of hard-coded dependencies, thus making it possible to remove or change them at run time. This ability to modify dependencies at run time allows us to create isolated environments that are ideal for testing.
We can replace real objects in production environments with mocked ones for testing environments. Functionally, the pattern injects depended-upon resources into the destination when needed by auto- matically looking up the dependency in advance and providing the destination for the dependency.
As we write components dependent upon other objects or libraries, we will describe its dependencies. At run time, an injector will create instances of the dependencies and pass them along to the dependent consumer. When any of our modules boot up at run time, the injector is responsible for actually instantiating the instance of the object and passing in any of its required dependencies. For instance, this simple app declares a single module and a single controller, like so: angular.
AngularJS uses an annotate function to pull properties off of the passed-in array during instantia- tion. Annotation by Inference Angular assumes that the function parameter names are the names of the dependencies, if not otherwise specified. The injection process looks like: injector.
JavaScript minifiers generally change function arguments to the minimum number of characters along with changing white spaces, removing new lines and comments, etc. If we do not explicitly describe the arguments, Angular will not be able to infer the arguments and thus the required injectable. Explicit Annotation Angular provides a method for us to explicitly define the dependencies that a function needs upon invocation.
This method allows for minifiers to rename the function parameters and still be able to inject the proper services into the function. This method of injection does work with minification, because the annotation information will be packaged with the function. Inline Annotation The last method of annotation that Angular provides out of the box is the inline annotation.
Additionally it affords us the ability to not use a temporary variable in the definition. Inline annotation allows us to pass an array of arguments instead of a function when defining an Angular object. The elements inside this array are the list of injectable dependencies as strings, the last argument being the function definition of the object. We often refer this method as the bracket or array notation []. The annotate function is used by the injector to determine which services will be injected into the function at invocation time.
The annotate method returns a single array of the names of services that will be injected into the function at the time of invocation. Dependency Injection has The has method returns true if the injector knows that a service exists in its registry and false if it does not.
It takes a constructor and invokes the new operator with all of the arguments specified. The instantiate method returns a new instance of Type. The arguments for the function are set with the function annotation. The invoke method returns the value that the fn function returns. In production, however, it is often less convenient to explicitly concern ourselves with order of arguments and code bloat.
The ngMin tool allows us to alleviate the responsibility to define our dependencies explicitly. It walks through our Angular apps and sets up dependency injection for us.
For instance, it will turn this code: angular. If we are using Rails, we can use the Ruby gem ngmin-rails. With the help of astral, an AST tooling framework, it rebuilds the source with the necessary annotations and then dumps the updated source using escodegen.
If our code uses syntax similar to the code used in this book, ngMin will be able to parse the source and pre-minify it. For memory and performance purposes, controllers are instantiated only when they are needed and discarded when they are not.
That means that every time we switch a route or reload a view, the current controller gets cleaned up by Angular. Services provide a method for us to keep data around for the lifetime of the app and communicate across controllers in a consistent manner. They provide an interface to keep together those methods that relate to a specific function. It will also be useful to make our own services for any decently complex application. Within the first few minutes, you'll know enough to have an app running.
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.
You'll learn core Angular concepts - from how Angular works under the hood, to rich interactive components, from in-depth testing to real-world applications. Learn Angular best practices, such as: testing, code organization, and how to structure your app for performance. We'll walk through practical, common examples of how to implement complete components of your applications.
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. Do I have to know Angular 1? Chapters include common problems and how to avoid them. Save my name, email, and website in this browser for the next time I comment. Notify me of follow-up comments by email. Notify me of new posts by email. This site uses Akismet to reduce spam.
Learn how your comment data is processed. Programmer Books. Web development Angular Books. Introducing Materialize.
0コメント