یک پردیس

۶ مطلب با کلمه‌ی کلیدی «AngularJS» ثبت شده است

Forms

Building Forms

Take this code in HTML:

<form ng-controller='formController'>
    <input type='text' name='First' ng-model='formValues.first'>First Name</input>
    <input type='text' name='Last' ng-model='formValues.last'>Last Name</input>
    <input type='text' name='Email' ng-model='formValues.email'>Email</input>
    <select name='Gender' ng-model='formValues.gender'>
        <option value='Male'>Male</option>
        <option value='Female'>Female</option>
    </select>
</form>

This can be handled like this:

var myApp = angular.module('myApp', [])
myApp.controller('formController', function($scope){
    $scope.formValues = {}
})

Submitting a Form

You will need ng-submit:

<form ng-controller='formController'>
    <input type='text' name='First' ng-model='formValues.first'>First Name</input>
    <input type='text' name='Last' ng-model='formValues.last'>Last Name</input>
    <input type='text' name='Email' ng-model='formValues.email'>Email</input>
    <select name='Gender' ng-model='formValues.gender'>
        <option value='Male'>Male</option>
        <option value='Female'>Female</option>
    </select>
    <button type='submit' ng-submit='submit()'>Submit</button>
</form>

And, if we were posting this data to a server, we would use the $http to pass the value that received the input data:

var myApp = angular.module('myApp', [])
myApp.controller('formController', function($scope){
    $scope.formValues = {}
    $scope.submit = function(){
        $http.post('/someApi', formValues).then(function(response){
            console.log(response)
        })
    }
})

Front-end Form Validation

There are 4 basic types of validation:

1. Required: whether the user has entered data -> HTML5 attribute required

2. Type Validation: validation against a pattern -> HTML5 type='email' or type='number'

3. Length Validation: has entered enough characters

4. Pattern Validation: the most advanced. checks against a regular expression

Angular Validation

Angular monitors the state of form and input fields (input, textarea, select), and notifies you about the current state.

States that can be applied to input fields, and are either true or false:

$untouched: The field has not been touched yet.

$touched: The field has been touched.

$pristine: The field has not been modified yet.

$dirty: The field has been modified.

$invalid: The field content is not valid.

$valid: The field content is valid.

States that can be applied to entire forms:

* $pristine: No fields have been modified yet.

* $dirty: One or more have been modified.

* $invalid: The form content is not valid.

* $valid: The form content is valid.

* $submitted - The form is submitted.

CSS classes that get applied by Angular for input fields:

* ng-untouched: The field has not been touched yet.

* ng-touched: The field has been touched.

* ng-pristine: The field has not been modified yet.

* ng-dirty: The field has been modified.

* ng-valid: The field content is valid.

* ng-invalid: The field content is not valid.

* ng-valid-key: One key for each validation. For example: ng-valid-required; this is useful when there is more than one thing that must be validated.

* ng-invalid-key: For example: ng-invalid-required

CSS classes that get applied by Angular for entire forms:

* ng-pristine: No fields have been modified yet.

* ng-dirty: One or more fields have been modified.

ng-valid: The form content is valid.

ng-invalid: The form content is not valid.

ng-valid-key: One key for each validation. For example: ng-valid-required; this is useful when there is more than one thing that must be validated.

ng-invalid-key: Example: ng-invalid-required

Example

<form name='thisForm'>
    <input name="thisName" ng-model="thisName" required ng-pattern='/^([^0-9]*)$/'>
    <span ng-show="thisForm.thisName.$touched && thisForm.thisName.$invalid">
Oops! This field is required.
</span> <input type='email' name='thisEmail' required> <span ng-show="thisForm.thisEmail.$touched && thisForm.thisEmail.$invalid">
Oops! Please enter a valid email address.
</span> <button type='submit' ng-disabled='thisForm.thisName.$invalid' ng-submit='submit()'>
Submit
</button> </form>

Week Five Sample Code


Week One Week Two Week Three Week Four Week Five

Promises

In order to properly use asynchronous operations in your Angular code, use promises. Prior to introduction of promises, people used callback functions.

* Promises are provided by $q service.

* Instantiating a promise is basically telling JS to "wait for this to finish".

* You wrap logic inside the promise, with calls to resolve() instead of return.

* Where your normal function would return a final value, the async method returns a promise of having the value in the future.

* As promise.then() and promise.catch() return promises, they can be chained in an operation called composition. Composition refers to the execution of several async calls in parallel and getting the result, once all the promises have been resolved.

Promise States

* Pending: an initial state, not fulfilled or rejected

* Fulfilled: the operation completed successfully

* Rejected: the operation failed

* Settled: the operation is either fulfilled or rejected, but not pending

* Resolved: the promise is settled or locked into a promising chain

Using Promises

Declaring Promises

angular.module('myApp', [])
myApp.service('myService', ['$q', function($q){
    
}])

Then there are two ways to declare your promise, $q.when() or $q.defer(). These methods serve different purposes, $q.when() can turn any value-based function into a promise, whose return value can then be used. It is primarily useful for situations where a 3rd party promise (such as jQuery's), is being used in a library. $q.defer() - on the other hand - declares a standalone promise that will resolve with whatever data you pass to it through $q.resolve or $q.reject.

//These are the two methods of declaring promises.
//For all intents and purposes these declarations
//are the same, other than the reasons listed above. //$q.defer() method function demonstrateDefer(){ var deferred = $q.defer() $http.get('someresource').then(function(response){ $q.resolve(response) }) return $q.promise() } //$q.when() method function someOtherFunction(){ return $http.get('someresource') } $q.when(someOtherFunction()).then(function(){ })

Promise Return Value

To use a promises return value, you make use of the .then() method on the promise object.

It can either only do something on success:

httpResponseFunction().then(function(response){
    doStuffWithReponse(response)
})

Or it can have an additional function passed to it to handle failures:

httpResponseFunction().then(function(response){
    doStuffWithResponse(response)
}, function(error){
    handleErrors(error)
})

Chaining and Combining Promises

Chaining promises is one of the most powerful features of $q. Simply put, a return value from a then()statement passes to the next then() statement in the promise.

function deferThis(){
    var deferred = $q.defer()
    $http.get('something').then(function(response){
        deffered.resolve(response)
    })
    return deferred.promise
}
function passTheBuck(response){
    deferThis.then(function(response){
        doStuffWithResponse(response)
    })
}

Rejecting promises can happen at any point in the chain cleanly, causing each error callback below where it was called to be fired.

function deferThis(){
    //If the failure occurs within this promise, errorhandle1() will be called
    var deferred = $q.defer()
    $http.get('something').then(function(response){
        deffered.resolve(response)
    }, function(error){
        errorHandle1(error)
    })
    return deferred.promise
}

function passTheBuck(){
    //If the failure occurs here, errorhandle1() and errorhandle2() will be called,
//but not errorhandle3() var deferred2 = $q.defer() deferThis.then(function(response){ deferred2.resolve(response) }, function(error){ errorHandle2(error) }) return deferred2.promise } function passMoreBucks(){ //If the failure occurs here,
//errorhandle1(), errorhandle2(), and errorhandle3() will all be called passTheBuck.then(function(response){ console.log(response) }, function(error){ errorhandle3(error) }) }

Combining promises makes use of the .all() method.

function deferThis(){
    var deferred = $q.defer()
    $http.get('something').then(function(response){
        deffered.resolve(response)
    }, function(error){
        errorHandle1(error)
    })
    return deferred.promise
}

function deferAnother(){
    var deferred = $q.defer()
    $http.get('something').then(function(response){
        deffered.resolve(response)
    }, function(error){
        errorHandle1(error)
    })
    return deferred.promise
}

$q.all(deferThis(), deferAnother()).then(function(response){
    promiseOneReturnFunction(response[0])
    promiseTwoReturnFunction(response[1])
})

AJAX Calls in Angular

$http

The $http service is a function that takes a single argument (a configuration object) that generates an HTTP request and returns a promise. This promise will be resolved to a response object when the request succeeds or fails. The configuration object is the object describing the request to be made and how it should be processed.

The response object has these properties:

* Data: {string|Object}, The response body transformed with the transform function

* Status: {number},  HTTP status code of the response

* Headers: {function([headerName])}, Header getter function

* Config: {Object}, The configuration object that was used to generate the request

* StatusText: {string}, HTTP status text of the response

You can use $http like this:

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': undefined
 },
 data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});

Check out $http documentation for more information on other parameters you can use in configuration object.

Also, there are some shortcuts for common cases:

$http.get

$http.post

$http.head

$http.put

$http.delete

$resource

This service allows you to create convenient methods for dealing with RESTful APIs.

Declare it like this:

var resource = $resource(url, [paramDefaults], [actions], options);

For example:

$resource('http://example.com/resource/:resource_id.:format')

Week Four Sample Code


Week One Week Two Week Three Week Four Week Five

Expressions and Built-in Directives

Angular expressions bind application data to an HTML element using functions such as operators, literals, and variables that are similar to JavaScript. Unlike JavaScript expressions, Angular expressions can be written inside HTML. An Angular expression can be written as {{expression}} or written inside a directive, such as ng-bind=expression.

Common Expressions

1. Bind a basic value: {{value}}

2. Bind a property of an object: {{object.property}}

3. Check for true/false: {{boolean == true}} or {{!boolean}}

ng-show and ng-hide

This directive invokes hide in CSS to show/hide an element. An example:

<div ng-show='truthyValue == true'>
Show this text using ng-show
</div>
<div ng-hide='truthyValue == true'>
Hide this text using ng-hide
</div>

ng-if

With this directive, we can decide whether the DOM will render an element based on an Angular expression. An example:

<div ng-if='truthyValue == true'>
This will be rendered by the DOM if truthyValue == true
</div>

* Difference between ng-if and ng-hide is about HTML rendering. In ng-if, if the expression in false, it will not render at all.

ng-class

This directive will inject a class into a HTML element based on an Angular expression; in other words, it will behave according to the evaluated expression in three ways:

1. String -> string will represent class names. Use space for more than one class.

2. Object -> every key/value pair of the object will be a value/class name. ("truthyvalue": "className")

3. Array -> each element of the array will either be as the type 1 or the type 2.

ng-style

This directive will inject inline CSS into an element. For example:

For this object (scope value):

$scope.manualStyle = {
    'background-color': 'blue'
}

The markup would look like this:

<div ng-style='manualStyle'>
This has a blue background
</div>

Arrays

To display the list use the ng-repeat directive. To filter the list you could add a two-way bound textbox allowing the user to enter text by which to filter. To expand your list add another two-way bound textbox and push that property value to your array of items when the user clicks a button. To remove items you can pass the index of the item to a function that just removes the item from the array. Parameters in the ng-repeat expression allow you to filter and order your list.

No matter what you do to the array with ng-repeat your repeated section of HTML would update accordingly, reflecting each item in the list properly.

ng-repeat

We can iterate through lists of objects using this directive. For example, take this list:

$scope.students = [
{'name': 'Pardis', 'age': '22', 'GPA': '4.0'},
{'name': 'Farbod', 'age': '23', 'GPA': '2.5'},
{'name': 'Giti', 'age': '19', 'GPA': '3.8'}
];

In HTML:

<div ng-repeat="std in students">
Name: {{std.name}}, Age: {{std.age}}, GPA: {{std.GPA}}
</div>

$index is a built-in variable to ng-repeat that will reference the index value of the item in the array.

* $parent, if used with nested ng-repeats, will get the repeat above it without having to use the variable name of the parent repeat.

Filter

In case we have something like this:

$scope.filterVal = 'Pardis'

And we write this in HTML:

<div ng-repeat="std in students | filter: filterVal">
Name: {{std.name}}, Age: {{std.age}}, GPA: {{std.GPA}} 
</div>

Only object with filterVal in it will render.

If we write this:

<div ng-repeat="std in students | orderBy: 'name'">
Name: {{std.name}}, Age: {{std.age}}, GPA: {{std.GPA}} 
</div>

the list will be shown in a sorted way by name. Furthermore, orderBy: '!Name' will reverse the order.

If you use track by, you will prevent re-rendering already present elements. For example:

<div ng-repeat="std in students | orderBy: 'name' | filter: filterVal track by $index">
Name: {{std.name}}, Age: {{std.age}}, GPA: {{std.GPA}}
</div>

ng-option

This directive allows us to create dynamic <option> lists within a ng-option. For example in this array:

$scope.students = [
{'name': 'Pardis', 'age': '22', 'GPA': '4.0'},
{'name': 'Farbod', 'age': '23', 'GPA': '2.5'},
{'name': 'Giti', 'age': '19', 'GPA': '3.8'}
];

In HTML:

<select ng-options="std.name for std in students" ng-model="selected"></select>

Will generate:

<select ng-model='selected'>
<option value='Pardis'>Pardis</option>
<option value='Farbod'>Farbod</option>
<option value='Giti'>Giti</option>
</select>

And std.name in ng-options will be responsible for what will serve as value in <option>.

Week Three Sample Code


Week One Week Two Week Three Week Four Week Five

MVVM Overview

Angular is an implementation of MVVM (Model-View-ViewModel) design pattern.

MVVM is different from MVC because it allows for two-way data binding between the model and the view. For example, an input field could be modified by a user, which will cause the data in the model to change, or a change within the model can cause the input data to reflect different data instead.

Model

* The model is the source of data, or the data itself.

* Usually encapsulated in Services, Factories, or Constants in Angular.

View

* The view is what the user sees and interacts with.

* Angular provides a dynamic view on the web page.

ViewModel

* The view-model binds the data from the model to the view and vice versa.

* In Angular, it is encapsulated by the $scope variable, which is decorated by a funtion called a Controller.

Controllers Overview

Controllers are a JavaScript constructor function. They control the view-model contained within the Angular scope.

Angular invokes the controller with a $scope object. The role of controllers in Angular is to expose data to our view via $scope, and to add functions to $scope that contain business logic that enhances view behavior.

Usages

1. Set the initial state of scope variable.

2. Add behavior to scope by two-way binding variables and declaring scope functions.

3. Set up communications to and from view and model through dependency injection.

Creating a Controller

var app = angular.module("app", [])
.controller("myController", [
     "$scope",
     function($scope) {
         // do work here
     }
]);

We can use ng-controller="myController" in HTML:

<body ng-controller="myController"> ... </body>

We can also nest them and create separte scopes which are shared by means of scope:

<body ng-controller="pageController">
    <div ng-controller='myChildController'>
        <div ng-controller='evenDeeperController'>
        </div>
    </div>
</body>

In order to avoid collision, we can use controller as:

<body ng-controller="SettingsController1 as settings">
{{settings.sampleScopeVariable}}
</body>

Scope Overview

$scope is used to make the model available to the view. It is also referred to as the view-model.

Properties

To define Scope variables, simply assign them as subproperties of the $scope object.

var app = angular.module("app", [])
.controller("myController", [
    "$scope",
    function ($scope) {
        $scope.name = "aName";
    }
]);



Scope properties can be any standard JS objects.

$scope.person = {
    firstName: "fName",
    lastName: "lName"
};

Methods

For adding a method that your view can use:

var app = angular.module("app", [])
.controller("myController", [
    "$scope",
    function ($scope) {
        $scope.title = "Home";
        $scope.renameTitle = function (newValue) {
            $scope.title = newValue;
        };
    }
]);

Or:

var app = angular.module("app", [])
.controller("myController", [
    function ($scope) {
        $scope.title = "Home";
        function renameTitle(newValue) {
            $scope.title = newValue;
        }
        $scope.renameTitle = renameTitle;
});

In HTML:

<div ng-controller='myController'>
    <h1>{{title}}</h1>
    <a href='#' ng-click='renameTitle("Away")'>Click This to Change</a>
</div>

* For two-way dynamic binding you should use ng-model:

<textarea class="form-control" ng-model="model.specialInstructions"></textarea>

Week One Week Two Week Three Week Four Week Five

What is Angular?

AngularJS is an open-source JavaScript application development framework. What a framework does is to provide us a top-level access to some of the lower-level functions in JavaScript. What AngularJS does is better than jQuery: it provides a different work flow.

AngularJS is especially usefull when you have data-heavy applications where the data changes frequently. AngularJS gives us an architectural pattern that we can follow as well as the utility to actually be able to interact with data.

Setting Up

Put these two lines just before </body>:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script></script>

Modules and Dependency Injection

Our Very First Module

When talking about coding, we have three main files which I will name them JS, CSS, and HTML. First, we should put this into JS:

var app=angular.module('testApp', []);

Then we can create our controller in JS:

app.controller('testController',
    function($scope /* the scope of the controller */) {
    $scope.test = 'hello'; // declare a test variable in scope
);

In HTML, inside body, put this:

<div ng-app='testApp' ng-controller='testController'></div>

"ng-app" tells angular to load testApp module onto this <div>, and "ng-controller" binds "test" variable to this <div>.

Inside this <div>, you can use {{test}}.

Basic Dependency Injection

Dependency injection practically means including something else into that controller. In Angular, DI allows us to share variables and functions between self-contained modules without having to reuse code, and maintains the state of each component. Let's declare a constant:

app.constant('testConstant',  'constantValue');

Then we inject this constant into our controller by changing controller like this:

app.controller('testController',
function($scope, testConstant) { $scope.test = 'hello'; $scope.constant = testConstant; });

Then we should be able to put constant value in HTML by {{constant}}.

Week One Code Sample


Week One Week Two Week Three Week Four Week Five