1,利用angular特性构建简单的购物车
下面的代码是将html和controller.js和在一起方便阅读。

<html ng-app>
<head>
  <title>购物车</title>
</head>
<body ng-controller='ctrl'>
<h1>购物车</h1>
<div ng-repeat='item in items'>
  <span>{{item.title}}</span>
  <input ng-model='item.quantity'>
  <span>{{item.price | currency}}</span><!--将价格通过过滤器currency进行转换,并且自动计算-->
  <span>{{item.price * item.quantity | currency}}</span><!--angular自动计算价格-->
  <button ng-click="remove($index)">删除</button>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
  function ctrl($scope) {<!--ctrl定义数组初始值-->
    $scope.items = [
      {title: '罐头', quantity: 8, price: 3.95},
      {title: '可乐', quantity: 17, price: 12.95},
      {title: '雪碧', quantity: 5, price: 6.95}
    ];
    $scope.remove = function(index) {
      $scope.items.splice(index, 1);
    };
  }
</script>
</body>
</html>

页面显示效果:
购物车1
购物车2
2,利用angular特性构建简单的邮件界面

index.html
<!doctype html>
<html ng-app="AMail">
  <head>
    <script src="js/angular.js"></script>
    <script src='controllers.js'></script>
    <meta Content-Type="text/html;charset=UTF-8">
    <title>Mike的邮件</title>
  </head>
  <body>
    <h1>我的邮件</h1>
    <div ng-view></div>
  </body>
</html>

list.html

<head>
    <meta Content-Type="text/html;charset=UTF-8">
</head>
<body>


<table border="1px solid">
  <tr>
    <td><strong>发信人</strong></td>
    <td><strong>邮件主题</strong></td>
    <td><strong>发信日期</strong></td>
  </tr>
  <tr ng-repeat='message in messages'>
    <td>{{message.sender}}</td>
    <td><a ng-href='#/view/{{message.id}}'>{{message.subject}}</a></td><!--通过id查找邮件-->
    <td>{{message.date}}</td>
  </tr>
</table>


</body>

detail.html
<!doctype html>
<html>
<head>
    <meta Content-Type="text/html;charset=UTF-8">
</head>
<body>


<div><strong>邮件主题:</strong> {{message.subject}}</div>




<div><strong>发信人:</strong> {{message.sender}}</div>




<div><strong>发信日期:</strong> {{message.date}}</div>




<div>
  <strong>收信人:</strong>
  <span ng-repeat='recipient in message.recipients'>{{recipient}} </span>
</div>




<div>{{message.message}}</div>


<a href='#/'>返回邮件列表</a>
</body>
</html>

controller.js

// Create a module for our core AMail services
var aMailServices = angular.module('AMail', []);

// Set up our mappings between URLs, templates, and controllers
function emailRouteConfig($routeProvider) {//定义路由
  $routeProvider.
    when('/', {
      controller: ListController,//默认找到所有的list数据,将整个集合messages全部显示出来
      templateUrl: 'list.html'
    }).
// Notice that for the detail view, we specify a parameterized URL component
// by placing a colon in front of the id
    when('/view/:id', {
      controller: DetailController,
      templateUrl: 'detail.html'
    }).
    otherwise({
      redirectTo: '/'
    });
}

// Set up our route so the AMail service can find it 定义路由路径,方便angular查找
aMailServices.config(emailRouteConfig);

// 模拟假email数据
messages = [{
  id: 0, sender: 'jean@qq.com', subject: '你好,朋友!',
  date: 'Dec 7, 2015 12:32:00', recipients: ['mike@qq.com'],
  message: 'Hi greg,什么时候有时间啊,要不一起玩?'
    +'我们好久都没有联系了!'
}, {
  id: 1,  sender: 'maria@qq.com',
  subject: '你在哪儿?',
  date: 'Dec 7, 2014 8:15:12', recipients: ['mike@qq.com'],
  message: '你在哪儿啊,打你的电话没人接.'
    +'是不是电话没电了?'
}, {
  id: 2, sender: 'bill@qq.com', subject: 'AngularJs学习',
  date: 'Dec 6, 2013 20:35:02', recipients: ['mike@qq.com'],
  message: '最近在学习angular,感觉要学的东西太多了.'
    +'好多东西都不知道呢.'
} ];

// Publish our messages for the list template
function ListController($scope) {
  $scope.messages = messages;
}

// Get the message id from the route (parsed from the URL) and use it to
// find the right message object.
function DetailController($scope, $routeParams) {
  $scope.message = messages[$routeParams.id];
}

页面显示:
email
email2
3,angular怎样同服务端进行通信
首先引入express

index.html

<!doctype html>
<html lang='en' ng-app>
  <head>
    <title>Shopping car</title>
    <meta Content-Type="html/text;charset=UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  </head>
  <body ng-controller="ctrl">
    <h1>shop</h1>
    <table>
      <tr ng-repeat="item in items">
        <td>{{item.title}}</td>
        <td>{{item.description}}</td>
        <td>{{item.price | currency}}</td>
      </tr>
    </table>
    <script>
      function ctrl($scope, $http) {
        $http.get('/products').success(function(data, status, headers, config) {
          $scope.items = data;
        });
      }
    </script>
  </body>
</html>

服务端入口文件 node server.js
server.js
//创建express应用,express() 函数是express模块所输出的最高级别的函数,参考:http://expressjs.com/4x/api.html
var express = require('express');//引入express框架
var app = express();

app.use("/", express.static(__dirname));//__dirname 在任何模块文件内部,"__dirname"变量获取当前模块文件所在目录的完整绝对路径。
//方法:express.static(root, [options]) The root argument refers to the root directory from which the static assets are to be served.

var products = [//定义数据源集合
  {id: 0, title: 'Paint pots', description: 'Pots full of paint', price: 3.95},
  {id: 1, title: 'Polka dots', description: 'Dots with that polka groove', price: 12.95},
  {id: 2, title: 'Pebbles', description: 'Just little rocks, really', price: 6.95}
];

app.get('/products', function(req, res) {//
  res.send(products);// respond with "products" array when a GET request is made to the homepage 当主页发送get请求,服务器返回products集合
});
//app.set('title', 'My Site');
//app.get('title');
// => "My Site"

app.get('/products/:id', function(req, res) {
  res.send(products[req.params.id]);
});
//An object containing properties mapped to the named route “parameters”. 
//For example, if you have the route /products/:id, then the “id” property is available as req.params.id. This object defaults to {}.

app.listen(3000);
console.log('Listening on port 3000');

页面展示:
structures
pages
4.$index表示数组下标,从0开始

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  </head>
  <body>
    <table ng-controller='AlbumController'>
      <tr ng-repeat='track in album'>
        <td>{{$index + 1}}</td><!--下标从0开始-->
        <td>{{track.name}}</td>
        <td>{{track.duration}}</td>
      </tr>
    </table>
    <script>
      var album = [{name:'Southwest Serenade', duration: '2:34'},
                   {name:'Northern Light Waltz', duration: '3:21'},
                   {name:'Eastern Tango', duration: '17:45'}];

      function AlbumController($scope) {
        $scope.album = album;
      }
    </script>
  </body>
</html>

页面展示:
$index
5.1,利用ngClass改变样式

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <style type="text/css">
    .error {
      background-color: red;
    }
    .warning {
      background-color: yellow;
    }
    </style>
  </head>
  <body>
    <div ng-controller='HeaderController'>
      <div ng-class='{error: isError, warning: isWarning}'>{{messageText}}</div>
<!--The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.-->
      <button ng-click='showError()'>点击显示错误</button>
      <button ng-click='showWarning()'>点击显示提醒</button>
    </div>
    <script>
      function HeaderController($scope) {
        $scope.isError = false;
        $scope.isWarning = false;
        $scope.showError = function() {
          $scope.messageText = 'This is an error!';
          $scope.isError = true;
          $scope.isWarning = false;
        };

        $scope.showWarning = function() {
          $scope.messageText = 'Just a warning.  Please carry on.';
          $scope.isWarning = true;
          $scope.isError = false;
        };
      }
    </script>
  </body>
</html>

页面显示:
p1
p2

5.2,ng-class选择改变颜色

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <style type="text/css">
      .selected {
        background-color: lightgreen;
      }
    </style>
    <meta Content-Type="html/text;charset=utf-8"/>
    <title>利用ngClass点击选择改变颜色</title>
  </head>
  <body>
    <table ng-controller='ctrl'>
      <tr ng-repeat='restaurant in directory' ng-click='selectRestaurant($index)'
          ng-class='{selected: $index==selectedRow}'>
        <td>{{restaurant.name}}</td>
        <td>{{restaurant.cuisine}}</td>
      </tr>
    </table>
    <script>
      function ctrl($scope) {
        $scope.directory = [{name:'后街', cuisine:'烧烤'},
          {name:'关谷步行街', cuisine:'沙拉'},
          {name:'简朴寨', cuisine:'海鲜'}];

        $scope.selectRestaurant = function(row) {
          $scope.selectedRow = row;
        };
      }
    </script>
  </body>
</html>

页面显示:
ngClass2

6,点击聚焦

<!doctype html>
<html lang='en' ng-app='app'>
  <head>
    <title>Get focused</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  </head>
  <body ng-controller="ctrl">
    <button ng-click="clickUnfocused()">
      Not focused
    </button>
    <button ngbk-focus ng-click="clickFocused()">
      I'm very focused!
    </button>
    <div>{{message.text}}</div>
    <script>
      function ctrl($scope) {
        $scope.message = { text: 'nothing clicked yet' };
        $scope.clickUnfocused = function() {
          $scope.message.text = 'unfocused button clicked';
        };
        $scope.clickFocused = function() {
          $scope.message.text = 'focus button clicked';
        };
      }
      var appModule = angular.module('app', []);
      appModule.directive('ngbkFocus', function() {
        return {
          link: function(scope, element, attrs, controller) {
            element[0].focus();
          }
        };
      });
    </script>
  </body>
</html>

页面显示:
focus
7,ng-disabled
ng-disabled(true):动作被禁止,If the expression is truthy, then the disabled attribute will be set on the element
下面的demo,点击click,按钮自动禁止

<label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
<button ng-model="button" ng-disabled="checked">Button</button>

8,表单验证,防止重复提交

<!doctype html>
<html lang='en' ng-app>
  <head>
    <title>注册个人信息,防止重复提交</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <style type="text/css">
    .ng-invalid {
      border-color: red;
    }
    </style>
  </head>

  <body>
    <h1>注册</h1>
    <form name='addUserForm' ng-controller="ctrl">
      <div ng-show='message'>{{message}}</div>
      <div>性: <input name='firstName' ng-model='user.first' required></div>
      <div>名: <input ng-model='user.last' required></div>
      <div>邮件: <input type='email' ng-model='user.email' required></div>
      <div>年龄: <input type='number'
                       ng-model='user.age'
                       ng-maxlength='3'
                       ng-min='1'></div>
      <div><button ng-click='addUser()'
      ng-disabled='!addUserForm.$valid'>提交</button></div><!--ng-disabled为true,按钮自动禁止提交,当addUserForm为true时,也就是form表单填写没有error,全部满足条件,button按钮才可以点击-->
    </form><!--提交按钮点击做了二件事情1,表单验证 2,出发函数addUser-->


<script>
    function ctrl($scope) {
      $scope.message = '';

      $scope.addUser = function () {
        // TODO for the reader: actually save user to database...
        $scope.message = 'Thanks, ' + $scope.user.first + ', we added you!';
      };
    }
  </script>


  </body>
</html>

页面显示:
form1
form2
9,购物车自动计算消费,打折

<!doctype html>
<html lang='en' ng-app>
  <head>
    <title>购物车(2)</title>
    <link href="bootstrap.css" rel="stylesheet">
    <meta Content-Type="html/text;charset=utf-8">
  </head>
  <body>
    <div ng-controller="ctrl">
      <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>
      </div>
      <div>总消费: {{totalCart() | currency}}</div>
      <div>打折: {{bill.discount | currency}}</div>
      <div>打折后消费: {{subtotal() | currency}}</div>
    </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>


<script>
    function ctrl($scope) {
      $scope.bill = {};
      $scope.items = [
        {title: '罐头', quantity: 8, price: 3.95},
        {title: '可口', quantity: 17, price: 12.95},
        {title: '橙汁', quantity: 5, price: 6.95}
      ];
      $scope.totalCart = function() {//计算购物车当前物品中的总价格
        var total = 0;
        for (var i = 0, len = $scope.items.length; i < len; i++) {
          total = total + $scope.items[i].price * $scope.items[i].quantity;
        }
        return total;
      };
      $scope.subtotal = function() {
        return $scope.totalCart() - $scope.bill.discount;
      };
      function calculateDiscount(newValue, oldValue, scope) {//计算打折的费用
        $scope.bill.discount = newValue > 100 ? 10 : 0;//消费大于100打折10块
      }
      $scope.$watch($scope.totalCart, calculateDiscount);
    }
  </script>


  </body>
</html>

<!doctype html>
<html lang='en' ng-app>
<head>
  <title>Shopping car(3)</title>
  <link href="bootstrap.css" rel="stylesheet">
  <meta Content-Type="html/text;charset=utf-8">
</head>
<body>


<div ng-controller="ctrl">
    <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>
    </div>
    <div>Total: {{bill.total | currency}}</div>
    <div>Discount: {{bill.discount | currency}}</div>
    <div>Subtotal: {{bill.subtotal | currency}}</div>
  </div>


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


<script>
    function ctrl($scope) {
      $scope.bill = {};
      $scope.items = [
        {title: 'Apple', quantity: 8, price: 3.95},
        {title: 'Fish', quantity: 17, price: 12.95},
        {title: 'Meat', quantity: 5, price: 6.95}
      ];
      var calculateTotals = function() {
        var total = 0;
        for (var i = 0, len = $scope.items.length; i < len; i++) {
          total = total + $scope.items[i].price * $scope.items[i].quantity;
        }
        $scope.bill.total = total;
        $scope.bill.discount = total > 100 ? 10 : 0;
        $scope.bill.subtotal = total - $scope.bill.discount;
      };
      $scope.$watch('items', calculateTotals, true);
    }
  </script>


</body>
</html>

<!doctype html>
<html lang='en' ng-app>
<head>
  <title>Shopping Cart(4)</title>
  <link href="bootstrap.css" rel="stylesheet">
</head>

<body>


<div ng-controller="CartController">
  <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>
  </div>
  <div>Total: {{bill.total | currency}}</div>
  <div>Discount: {{bill.discount | currency}}</div>
  <div>Subtotal: {{bill.subtotal | currency}}</div>
</div>


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


<script>
  function CartController($scope) {
    $scope.bill = {};

    $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.$watch(function() {
      var total = 0;
      for (var i = 0; i < $scope.items.length; i++) {
        total = total + $scope.items[i].price * $scope.items[i].quantity;
      }
      $scope.bill.total = total;
      $scope.bill.discount = total > 100 ? 10 : 0;
      $scope.bill.subtotal = total - $scope.bill.discount;
    });
  }
</script>


</body>
</html>

页面显示:
![shopping car][14]
10,点击颜色变灰(ng-click)

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <style type="text/css">
    .menu-disabled-true {
      color: gray;
    }
    </style>
    <meta Content-Type="html/text;charset=utf-8"/>
  </head>
  <body>
    <div ng-controller='ctrl'>
      <ul>
        <li class='menu-disabled-{{isDisabled}}' ng-click='stun()'>点击颜色变灰</li>
        <li ng-click='disintegrate()'>点击颜色不变</li>
      </ul>
    <div/>
    <script>
      function ctrl($scope) {
        $scope.isDisabled = false;

        $scope.stun = function() {
          // stun target, then disable menu to allow regeneration
          $scope.isDisabled = true;
        };
      }
    </script>
  </body>
</html>

页面显示:
click
11,ng-click点击排序(sorting)

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  </head>
  <meta Content-Type="html/text;charset=utf-8">
  <title>排序</title>
  <body>
    <table ng-controller='ctrl'>
      <tr>
        <td ng-click='sortByName()'>Name</td>
        <td ng-click='sortByDuration()'>Duration</td>
      </tr>
      <tr ng-repeat='track in album'>
        <td>{{track.name}}</td>
        <td>{{track.duration}}</td>
      </tr>
    </table>
    <script>
      function ctrl($scope) {
        $scope.album = [{name:'Southwest', duration: '20:34'},
                     {name:'Northern Light', duration: '31:21'},
                     {name:'Eastern Tango', duration: '17:45'},
                     {name:'Adem',duration:'43.64'},
                     {name:'Belly',duration:'11.32'},
                     {name:'Elleny Bell',duration:'10.25'},
                     {name:'Silly',duration:'12.25'}];

        $scope.sortByName = function () {//按照唱片首字母来排序 A-Z
          var sorter = function(a, b) {
            var A = a['name'], B = b['name'];
            return ((A < B) ? -1 : (A > B) ? +1 : 0);
          };

          $scope.album = $scope.album.sort(sorter);
        };

        $scope.sortByDuration = function () {//按照唱片的长度排序,默认升序排列
          var sorter = function(a, b) {
            var A = a['duration'], B = b['duration'];
            return ((A < B) ? -1 : (A > B) ? 1 : 0);
          };

          $scope.album = $scope.album.sort(sorter);
        };
      }
    </script>
  </body>
</html>

页面显示效果:
sorting1
sorting2
12,ng-change Evaluate the given expression when the user changes the input. The expression is evaluated immediately.
The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.

<script>
  angular.module('app', [])
    .controller('ctrl', ['$scope', function($scope) {
      $scope.counter = 0;
      $scope.change = function() {
        $scope.counter++;
      };
    }]);
</script>
<div ng-controller="ctrl">
  <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  <label for="ng-change-example2">Confirmed</label><br />
  <tt>debug = {{confirmed}}</tt><br/>
  <tt>counter = {{counter}}</tt><br/>
</div>

页面显示效果:
ng-change

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  </head>
  <body>
    <form ng-controller="ctrl">
      Starting: <input ng-change="computeNeeded()"<!--当input框发生改变的时候,on-change迅速改变绑定的内容-->
                       ng-model="funding.startingEstimate">
      Recommendation: {{funding.needed}}
    </form>
    <script>
      function ctrl($scope) {
        $scope.funding = { startingEstimate: 0 };//定义初始值,并且只能位数字,不支持字符串的输入

        $scope.computeNeeded = function() {
          $scope.funding.needed = $scope.funding.startingEstimate * 10;
        };
      }
    </script>
  </body>
</html>

页面显示效果:

ng-change/ng-submit

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  </head>
  <body>
    <form ng-submit="requestFunding()" ng-controller="ctrl">
      Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate">
      Recommendation: {{funding.needed}}
      <button>Fund my startup!</button>
    </form>
    <script>
      function ctrl($scope) {
        $scope.funding = { startingEstimate: 0 };
        $scope.computeNeeded = function() {
          $scope.funding.needed = $scope.funding.startingEstimate * 10;
        };
        $scope.requestFunding = function() {
          window.alert("Sorry, please get more customers first.");
        };
      }
    </script>
  </body>
</html>

页面显示效果:

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  </head>
  <body>
    <form ng-controller="ctrl">
      Starting: <input ng-model="funding.startingEstimate">
      Recommendation: {{funding.needed}}
    </form>
    <script>
      function ctrl($scope) {
        $scope.funding = { startingEstimate: 0 };
        computeNeeded = function() {
          $scope.funding.needed = $scope.funding.startingEstimate * 10;
        };
        $scope.$watch('funding.startingEstimate', computeNeeded);
      }
    </script>
  </body>
</html>

13,怎样插入items

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  </head>
  <body>
    <div ng-controller='ctrl'>
      <ul>
        <li ng-repeat='student in students'>
          <a ng-href='/student/view/{{student.id}}'>{{student.name}}</a>
        </li>
      </ul>
      <button ng-click="insertTom()">Insert Tom</button>
    </div>
    <script>
      var students = [{name:'Mary Contrary', id:'1'},
        {name:'Jack Sprat', id:'2'},
        {name:'Jill Hill', id:'3'}];

      function ctrl($scope) {
        $scope.students = students;

        $scope.insertTom = function () {
          $scope.students.splice(1, 0, {name:'Tom Thumb', id:'4'});//splice(index(位置),howmany(多少个),items(内容)) 方法向/从数组中添加/删除项目,然后返回被删除的项目。该方法会改变原始数组。
        };
      }
    </script>
  </body>
</html>

页面显示效果:


MichaelDuan
1.8k 声望39 粉丝

引用和评论

0 条评论