Difference between revisions of "Angular.JS"

From Logic Wiki
Jump to: navigation, search
m
 
m (1 revision imported)
 
(No difference)

Latest revision as of 14:27, 9 May 2016


Starting Up

It can be used by just including script file. It does not have dependency.

<script src="angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js"></script>

Basic Angular MVC.png

Sample Angular Usage

<html ng-app>
<head>
 <script src="angular.js"></script>
 <script src="controllers.js"></script>
</head>
<body>
 <div <b style="color:red">ng-controller='HelloController'</b>>
 <input <b style="color:red">ng-model='greeting.text'</b>>
 <p><b style="color:red">{{</b>greeting.text<b style="color:red">}}</b>, World</p>
 </div>
</body>
</html>

References

$location

In order to write to browser url $location can be used.

function HelloController($scope, <b style="color:red">$location</b>) {
 $scope.greeting = { text: 'Hello' };
 // use $location for something good here...
}

$scope

Aims the area between tags where ng-coltroller attribute inserted

$watch()

To update the field no matter how it gets updated, we want to use a $scope function called $watch()

In this case, we want to watch funding.startingEstimate and call computeNeeded() whenever it changes. We could then rewrite the StartUpController to use this technique:

function StartUpController($scope) {  
  $scope.funding = { startingEstimate: 0 };
  computeNeeded = function() {
    $scope.funding.needed = $scope.funding.startingEstimate * 10;  
   };
  $scope.$watch('<b style="color:brown;">funding.startingEstimate</b>', computeNeeded); } 

Note that the expression to watch is in quotes. Yes, it is a string. This string is evaluated as something called an Angular expression.

ng-bind

To bind a cariable to a control

<p ng-bind="greeting"></p> 

ng-change

ng-change is used to fire a method when something change on control

 <input ng-change="<b style=color:green;">computeNeeded()</b>" ng-model="funding.startingEstimate"> 

function StartUpController($scope) {  $scope.funding = { startingEstimate: 0 };
  $scope.<b style=color:green;">computeNeeded</b> = function() {    $scope.needed = $scope.startingEstimate * 10;  }; } 

ng-repeat

 <li ng-repeat='student in students'>    <a href='/student/view/{{student.id}}'>{{student.name}}</a>  </li> 

ng-submit

If you have a form that groups inputs, you can use the ng-submit directive on the form itself to specify a function to call when the form submits. We can extend our previous example to let the user request funding for her startup by clicking a button:

<form ng-submit="requestFunding()" ng-controller="StartUpController">

The ng-submit directive also automatically prevents the browser from doing its default POST action when it tries to submit the form.


For onclick, you’d use ng-click. For ondblclick, use ng-dblclick, and so on.


Shopping Cart Example

Let's see the code and then explain it line by line

<html ng-app='myApp'>
<head>
 <title>Your Shopping Cart</title>
</head>
<body ng-controller='CartController'>
 <h1>Your Order</h1>
 <div ng-repeat='item in items'>
 <span>{{item.title}}</span>
 <input ng-model='item.quantity'>
 <span>{{item.price | currency}}</span>
 <span>{{item.price * item.quantity | currency}}</span>
 <button ng-click="remove($index)">Remove</button>
 </div>
 <script src="angular.js"></script>
 <script>
 function CartController($scope) {
 $scope.items = [
 {title: 'Paint pots', quantity: 8, price: 3.95},
 {title: 'Polka dots', quantity: 17, price: 12.95},
 {title: 'Pebbles', quantity: 5, price: 6.95}
 ];
 $scope.remove = function(index) {
 $scope.items.splice(index, 1);
 }
 }
 </script>
 </body>
</html>

The following is a brief tour of what’s going on here. The rest of the book is dedicated to a more in-depth explanation.

Let’s start at the top:

 <html ng-app>

The ng-app attribute tells Angular which parts of the page it should manage. Since we’ve placed it on the <html> element, we’re telling Angular that we want it to manage the

whole page. This will often be what you want, but you might want to place it on a

within the app if you’re integrating Angular with an existing app that uses other methods to manage the page.

 <body ng-controller='CartController'>

In Angular, you manage areas of the page with JavaScript classes called controllers. By including a controller in the body tag, I’m declaring that CartController will manage everything between <body> and </body>.

 <div ng-repeat='item in items'>
The ng-repeat says to copy the DOM inside this
once for every element in an

array called items. On every copy of the div, it will also set a property named item to the current element so we can use it in the template. As you can see, this results in three

s each, containing the product title, quantity, unit price, total price, and a button

to remove the item entirely.

 <span>{{item.title}}</span>

As we showed in the “Hello, World” example, data binding via {{ }} lets us insert the value of a variable into part of the page and keep it in sync. The full expression Template:Item.title retrieves the current item in the iteration and then inserts the contents of that item’s title property into the DOM.

 <input ng-model='item.quantity'>

The ng-model definition creates data binding between the input field and the value of item.quantity.

The {{ }} in the sets up a one-way relationship that says “insert a value here.” We want that effect, but the application also needs to know when the user changes the quantity so it can change the total price.


We’ll keep changes in sync with our model by using ng-model. The ng-model declaration inserts the value of item.quantity into the text field, but it also automatically updates item.quantity whenever the user types a new value.

 <span>{{item.price | currency}}</span>
 <span>{{item.price * item.quantity | currency}}</span>

We want the unit price and total price to be formatted as dollars. Angular comes with a feature called filters that lets us transform text, and there’s a bundled filter called currency that will do this dollar formatting for us. We’ll look at filters more in the next chapter.

 <button ng-click='remove($index)'>Remove</button>

This allows users to remove items from their carts by clicking a Remove button next to the product. We’ve set it up so that clicking this button calls a remove() function. We’ve also passed in $index, which contains the iteration number of the ng-repeat, so we know which item to remove.

 function CartController($scope) {

This CartController manages the logic of the shopping cart. We’ll tell Angular that the controller needs something called $scope by putting it here. The $scope is what lets us bind data to elements in the UI.

 $scope.items = [
  {title: 'Paint pots', quantity: 8, price: 3.95},
  {title: 'Polka dots', quantity: 17, price: 12.95},
  {title: 'Pebbles', quantity: 5, price: 6.95}
 ];

By defining $scope.items, I’ve created a dummy data hash to represent the collection of items in the user’s shopping cart. We want to make them available to data bind with the UI, so we’ll add them to $scope. Of course, a real version of this can’t just work in memory, and will need to talk to a server to properly persist the data. We’ll get to that in later chapters.

 $scope.remove = function(index) {
  $scope.items.splice(index, 1);
 }

We want the remove() function available to bind in the UI, so we’ve added this to $scope as well. For the in-memory version of the shopping cart, the remove() function can just

delete items from the array. Because the list of
s created by ng-repeat is data

bound, the list automatically shrinks when items disappear. Remember, this remove()

function gets called from the UI whenever the user clicks on one of the Remove buttons.