You are on page 1of 13

Angular JS Server handles the views in part for application security.

Angular cannot be used to securely authenticate a user, as it exists entirely in the browsers execution. In the browser, the user is able to modify any part of the code provided to them. The server provides the browser with a cookie to identify the user session, and every transaction with the server will use that cookie to identify the user. In Public directory, when angular files are stored: App.js attaches an angular instance to the window as a window.app object, and defines module dependencies. Config.js sets up routing and other configuration options. Controllers directory contains all your application controllers, separated into their own files. Services directory contains all application services o Web service - a software function provided at a network address over the web or cloud. Directives.js contain directives. Filters.js contain filters Init.js provide some setup configuration.

Angular JS is not a library, it is a framework that embraces extending HTML into a more expressive and readable format. Specify that it is an angular app with ng-app directive. The ng-app will cause angular to auto-initialize your application. From ng-model directives, angular automatically sets up two-way data binding. (Model is bound to view, and view is bound to model) When page loads, angular bounds names of the input widgets (whats in ng-model) to variables of the same name. These variables are model components of the MVC design pattern. {{ }} angular markup for data binding. The braces are an expression , and it can be combined with a filter (the pipe character separates them). A filter provides a way of formatting display data. Angular JS Practices: Decouple DOM manipulation from App logic App testing is of equal importance to writing Decouple client side of app from server side

With angular you can bootstrap your app easily using services, which are auto injected into your application with dependency injection

Dependency Injection this is where dependencies are passed into functions as needed, at runtime. These dependencies can be asked for by the injector service, using injector.get(name of dependency), if the dependency isnt already assigned to a variable in the code. Things to Keep in Mind as you Learn Angular: Understand Modules before you start Understand Dependency Injection When your Controllers get Bigger, Learn Scope o How the magical data bindings is related to $socpe.watch(), and $scope.apply(); o How $scope is shared between its controller and child o When Angular will implicity create a new $scope o How the events ($scope.on, scope.emit, etc.) work as a communication among scopes. When you manipulate DOM in Controller, write Directives. Put control logic in directive controller, and DOM logic in link function; scope sharing is the glue. Angular.js Router might not be what you expected it works like a serverside router, and is built to work with ng-view. When a route is hit, a template is loaded and injected into ng-view and some controller can be instantiated. Angular JS: Binding Angular uses {{ }} expression to bind data to the view. Controllers Wrap DOM elements in a controller with ng-contoller. Everything encompassed in there has the scope of that controller. You then define a function in JS, and pass in $scope as a parameter. $scope defines the scope of that Controller. You can then pass in things and perform other manipulations. It is the code that controls that piece of DOM. The Dot This allows you to set properties on a reference to what is happening inside of a scope of a controller. Without that, if you just use message instead of data.message, then contents of message will be overwritten each time, Sharing Data between Controllers: You can share data between them, and bind them together by making the controllers share the same source of data. (set scope.data to the same variable)

Angular JS Concepts:
Client-Side Templates Template and data get shipped to the browser and assembled there. The role of the server becomes only to serve static resources for the templates and to properly serve the data required by those templates. Model View Controller (MVC) Have a clear separation in your code between managing its data (model), the application logic (controller), and presenting data to the user (view). o View gets data from the model to display to the user. When a user interacts with the application by clicking or typing, the controller responds by changing data in the model. Finally, the model notifies the view that a change has occurred so that it can update what it displays. o View is the Document Object Model (DOM), the controllers are JavaScript classes, and the model data is stored in object properties. Data Binding we declare which parts of the UI map to which data properties. Dependency Injection lets us follow a development style in which, instead of creating dependencies, our classes just ask for what they need. Directives you can write your templates as HTML. These directives declaratively set up how your application works or be used to create reusable components. o Ng-app tells angular which parts of the page it should manage. o Ng-controller manage areas of the page with JavaScript classes called controllers. The tag you declare a controller, that controller will manage everything encompassed in that tag. o Ng-repeat says to copy the dom inside the div once for every element in an array. o Ng-model creates data binding between the input field and the value of item.quantity. It also automatically updates item.quantity whenever the user types a new value. o Filters lets us transform and format text.

Invoking Angular load the angular.js library, tell angular which part of the DOM it should manage with the ng-app directive. MVC A model containing data that represents the current state of your application. (Can just be model variables) Views that display this data. Controllers that manage the relationship between your model and your views.

The right way to define a controller, is as part of a module, which provides a namespace for related parts of your application Ng-app=myApp Var myAppModule = angular.module(myApp, []); //Define the module myAppModule.controller(Text Controller, function() { }); //Define a controller as part of that module. Automatic Initialization if the ng-app directive is found then Angular will: Load the module associated with the directive Create the application injector (used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules) Compile the DOM treating the ng-app directive as the root of the compilation. This allows you to tell it to treat only a portion of the Dom as an angular application. Manual Initialization If you need more control over the initialization process, you can use manual bootstrapping method instead. You might need to do this if you are using script loaders or the need to perform an operation before angular compiles a page. Script loaders these js libraries can load in scripts both asynchronously and in parallel. Script loaders will perform better than through a script tag, even if you concatenate all your scripts into one file. Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by the $parse service. Evaluation of all properties are against the scope Expression evaluation is forgiving to undefined and null No control flow statements Filters you can pass result of expression evaluations through filter chains. $ - is simply a prefix that angular uses to differentiate its API names from others. Forms a form is a collection of controls (input, select, textarea) for the purpose of grouping related controls together. Ng-model directive provides the two-way databinding by synchronizing the model to the view MVC Pattern Summarized: Separate applications into distinct presentation, data, and logic components. Encourage loose coupling between these components.

Model depending on context, a model can refer to either a single object representing one entity (model called phones with value being array of phones), or the entire model for the application (all entities) A model is any data that is reachable as a property of an angular scope object. Name of the property is the model identifier and value is any JS object. Angular creates models implicitly (by creating a scope property and assigning it a suitable value) when processing the following template constructs. A JavaScript object stops being a model when: No Angular scope contains a property that references the object. All angular scopes that contain a property referencing the object become stale and eligible for garbage collection. Controller a JavaScript function that is used to augment instances of angular scope, excluding the root scope. Use Controllers to: Set up the initial state of a scope object Add behavior of the scope object For example, a controller can create a model, which can be referred to in a template. A controller shouldnt try to do too much. It should only contain the business logic needed for a single view. Encapsulate work that doesnt belong to controllers into services and then using these services in controllers via dependency injection. Do Not Use Controllers for: Any Kind of DOM Manipulation Input Formatting Output Formatting Sharing stateless or stateful code across controllers (use angular services instead) Managing the life-cycle of other components The controller directive is used to (implicitly) create a scope for our template (everything inside the div where you defined the controller), and the scope is augmented (managed) by the Controller. You can pass values into your controller through functions called in directives in your template.

Controller inheritance in Angular is based on Scope inheritance. There is the root scope (global) in Angular, and then every other scope defined. However, standard prototypical inheritance between 2 controllers doesnt work as we might expect, because controllers are not instantiated directly by Angular, but rather applied to the scope object.

View
The view is the DOM loaded and rendered in the browser, after Angular has transformed the DOM based on information in the template, controller, and model. To generate the View, angular gathers information from the Template; applies controller functions to associated Scope objects; links Model properties to the associated scope objects; then generates a transformed DOM, which is rendered in the browser.

Data Binding in Angular


Data-binding in Angular web apps is the automatic synchronization of data between the model and view components. Model is treated as single source of truth in your application. The view is a projection of the model at all times, when the model changes, the view reflects the change, and vice versa. Template uncompiled HTML along with any additional markup or directives. View is an instant projection of your model. The controller is completely separated from the view and unaware of it. Therefore it is easy to test your controller in isolation without the view and related DOM/browser dependency.

Filters
Angular filters format data for display to the user myApp.filter(name, function((you can inject services here if you want, by passing as parameter)) { return function(text) { //function definition. } }

you can use filter|[model name] with ng-repeat to serach for entries in an outputted. list orderBy: limitTo Filters allow you to declare how to transform data for display to the user within an interpolation in your template. The syntax is {{ expression | filterName: parameter1 : parameter }} Filters can also be chained with additional pipe methods in the binding. {{12.9 | currency | number:0 }} displays $13 you can define your own filter by applying .filter to the module you created and defining a function from there. Parameters are separated by colons.

Angular JS Services
Purpose is to generate a single object or function that represents the service to the rest of the application. That object or function is passed as a parameter to any other factory function which specifies a dependency on this service. When declaring a service, you will be provided with an instance of a function that can be invoked by simply appending () to the injected function reference. And you can use that wherever. When declaring a factory, you will be provided with the value that is returned by invoking the function reference.

Directives
A directive is a way to extend the functionality of HTML in reusable components. It is essentially a function, that executes when the Angular compiler finds it in the DOM. You can add a directive to your module with app.directive(name, callback to create directive)

Directives can create custom elements, but what is more common is custom attributes, which can add behavior. Restrict E (element), A(attribute), C (class) Template the html that will be the element. Link function where you put the behavior of what the attribute directive will do. Behaviors are the behaviors that we can link directives to so they fire when those events happen. Such as mouse rolling over an elment.

Communicate with Controllers from Directives We want to be able to call methods in the directive that are defined in the controller. $apply() parses the passed string and finds the method within scope. We can combine this by having a directive like enter=loadMoreTweets() and then calling it through scope.$apply(attrs.enter) in the directive definition. Directive to Directive Communication directives talk to each other by requiring each other. You do this through the require property in the return object of the directive, then you can reference it with the 4th argument of your link function. Transclusion if you want content to be carried over from the DOM to your directive. Use ng-transclude, to delimit where to insert the existing snippet of DOM into. Define transclude: true in your directive. And then include ngtransclude in the template part of your directive for where you want the HTML to go. Components and Containers directives can be broken into two categories, components and containers. Component uncomplicated behavior, essentially display the data passed in the attributes.

Container allows for differing content inside the container directive when multiple instances of the directive exist. Uses transclusion to achieve this. Uses the scope option inside the directive with the @ character to pass in arguments defined in the directive. Directive Communication: Communicate between directives using controllers. Angular JS Book Chapter 6: Directives With directives, you can extend HTML to add declarative syntax to do whatever you like. Use data-ng-<directive name> if you want your code to validate. Directive Definition Options: Restrict declare how directive can be used in a template as an element, attribute, class, comment, or any combination. o E = Element, A = Attribute, C = Class, M = Comment. Priority set the order of execution in the template relative to other directives on the element. Template specify an inline template as a string. templateUrl specify the template to be loaded by URL. o Angular lets you replace or wrap the content with a element that you provide. o If you want Replace if true, replace the current element. If false or unspecified, append the directive to the current element. Transclude lets you move the original children of a directive to a location inside the new template. Scope create a new scope for the directive rather than inheriting its parent scope. Controller create a controller, which publishes an API for communicating across directives. (Adds behavior to the scope)

Require require that another directive be present for this directive to function correctly. Link programmatically modify resulting DOM element instances, add event listeners, and set up data binding. Compile programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. When naming your directive, prefix them with something of your choice to prevent collisons. Define Directives in camelCase. Compile and Link are the two functions Angular uses to create the live view for your application. Angular initialization Process: Script Loads angular loads and looks for the ng-app directive to find the application boundries. Compile Phase angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directives rules (template, replace, transclude, etc.) and calls the compile function if exists. The result is a compiled template function, which will invoke the link functions collected from all of the directives. Essentially runs through Dom and compiles the template based on the rules specified in included directives. Link Phase angular then runs a link function for each directive. Link function typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times. Compile functions deal with transforming the template itself, and link functions deal with making a dynamic connection between model and view. Controllers When you have nested directives that need to communicate with each other, the way to do this is through a controller. Directive controller is different that a module controller.

Other directives can have this controller passed to them with the require property, and you use ^ before the directive name to go up the dom. Without it, angular will look for a named directive on the same element. Compiler first compile: traverses the Dom and collects all the directives. The result is a linking function. Then link: combine the directives with a scope and produce a live view.

Scope
A scope is an object that refers to the application model. Scopes have a hierarchical structure which mimic the DOM structure of an application. Scopes provide APIs ($watch) to observe model mutations. Scopes can be nested to isolate application components while providing access to shared model properties. A scope (prototypically) inherits properties from its parent scope. Defining the scope property in the directive and passing in an empty object will define a new scope for each instance of the directive. Isolate scope will define a new scope for a given directive, but will still inherit things from the scope it is inside, like a controller. It is still javascript. @ - get an attribute from the parent scope. It extracts the attribute by name, and assigns it to the scope. You use {{ }} in the directive html since it is a string. = - gets an object. A property on a scope that you bind to. & - allows you to invoke or evaluate an expression on the parent scope or whatever the directive is inside of. So all of these symbols allow you to still use methods and properties of parent scopes while defining an isolate scope for the directive. The point of the HTML that you put in the document is just as hooks or markup for what directives should act on it. Acts as a placeholder and way to pass info from controller to directive. The HTML that is actually there may not make it into the final DOM at all.

@ - will get attribute from the parent scope. It will be changed if there is a change in the parent scope, but will not update the parent scope. One way data binding. The attribute is a string so you need to use {{ }} when dealing with it. = - gets an object from the parent scope, and sets up two-way data binding. Any changes that happen on either, will update the other.

Application Structure and Organization


In controllers, instead of defining the functions on the $scope directly, assign them to this so that you can return $scope.<ctrlName> = this. That way when you call the methods in the directives, you prefix them with <ctrlName>.method, and you know exactly where the function came from. You could group all of your controllers and directives together when you are defining them in a named object, then pass that named object to app.directive() and app.controller() respectively. This method does not work with filters, however. You should break you application into multiple modules: Service Module for service declaration Directive Module for directive declaration Filter Module for filter declaration Application level module which depends on above modules, and has initialization code. A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. Configuration Block define values, factories, directives, filters, etc. All of the configuration that a module will need. Run Block code which is needed to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Modules can list other modules as dependencies, but depending on a module implies that required module needs to be loaded before the requiring module is loaded. A Unit Test is a way of instantiating a subset of the application in test and then applying a stimulus to it.

The View and the DOM

Angular.element you can create an element with angular.element, that you can insert into the DOM, and then find later without having to search for it. All references in Angular are always wrapped with jQuery or jqLite, they are never raw DOM references. Compile service takes an HTML string and compiles it into a template function. (within a directive) $index shows what iteration of a loop you are in. $event captures the event that happens on the directive. $log references angular logging capabilities.

You might also like