angularJs案例汇总
---恢复内容开始---
这里我会把学习过程中碰到的demo与大家分享,由浅入深,逐个分析。
Eg1:入门必备
1 <html ng-app="todoApp"> 2 <head> 3 <title>TO DO List</title> 4 <link href="bootstrap.css" rel="stylesheet" /> 5 <link href="bootstrap-theme.css" rel="stylesheet" /> 6 <script src="angular.js"></script> 7 <script> 8 //数据模型 9 var model = { 10 user: "Adam", 11 items: [{ action: "Buy Flowers", done: false }, 12 { action: "Get Shoes", done: false }, 13 { action: "Collect Tickets", done: true }, 14 { action: "Call Joe", done: false }] 15 }; 16 //定义全局的module []表示不引用其他module 17 var todoApp = angular.module("todoApp", []); 18 //module里面可以定义多个controller 拥有各自的$scope 19 todoApp.controller("ToDoCtrl", function ($scope) { 20 $scope.todo = model; 21 }); 22 23 </script> 24 </head> 25 26 <body ng-controller="ToDoCtrl"> 27 <div class="page-header"> 28 <h1> 29 {{todo.user}}'s To Do List 30 <span class="label label-default">{{todo.items.length}}</span> 31 </h1> 32 </div> 33 <div class="panel"> 34 <div class="input-group"> 35 <input class="form-control" /> 36 <span class="input-group-btn"> 37 <button class="btn btn-default">Add</button> 38 </span> 39 </div> 40 <table class="table table-striped"> 41 <thead> 42 <tr> 43 <th>Description</th> 44 <th>Done</th> 45 </tr> 46 </thead> 47 <tbody> 48 <tr ng-repeat="item in todo.items"> //常见指令 49 <td>{{item.action}}</td> <td><input type="checkbox" ng-model="item.done" /></td> //实现双向数据绑定 50 <td>{{item.done}}</td> 51 </tr> 52 </tbody> 53 </table> 54 </div> 55 </body> 56 57 58 </html>
我们可以看到angularJs很适合和bootstrap一起运用,他并不依赖其他类库。
Eg2:稍微有些复杂,对于刚学的同学
1 <!DOCTYPE html> 2 <html ng-app="todoApp"> 3 <head> 4 <title>TO DO List</title> 5 <link href="bootstrap.css" rel="stylesheet" /> 6 <link href="bootstrap-theme.css" rel="stylesheet" /> 7 <script src="angular.js"></script> 8 <script> 9 10 var model = { 11 user: "Adam", 12 items: [{ action: "Buy Flowers", done: false }, 13 { action: "Get Shoes", done: false }, 14 { action: "Collect Tickets", done: true }, 15 { action: "Call Joe", done: false }] 16 }; 17 18 var todoApp = angular.module("todoApp", []); 19 20 todoApp.controller("ToDoCtrl", function ($scope) { 21 $scope.todo = model; 22 //在该scope下定义函数 计算未完成的count 23 $scope.incompleteCount = function () { 24 var count = 0; 25 angular.forEach($scope.todo.items, function (item) { 26 if (!item.done) { count++ } 27 }); 28 return count; 29 } 30 31 $scope.warningLevel = function () { 32 return $scope.incompleteCount() < 3 ? "label-success" : "label-warning"; //count<3 className="label-success" 33 } 34 //该函数用于添加新事项 35 $scope.addNewItem = function (actionText) { 36 $scope.todo.items.push({ action: actionText, done: false }); 37 } 38 }); 39 40 </script> 41 </head> 42 <body ng-controller="ToDoCtrl"> 43 <div class="page-header"> 44 <h1> 45 {{todo.user}}'s To Do List 46 <span class="label label-default" ng-class="warningLevel()" //angularJs指令 用于确定该元素class 47 ng-hide="incompleteCount() == 0"> //如果为0 则hide 48 {{incompleteCount()}} 49 </span> 50 </h1> 51 </div> 52 <div class="panel"> 53 <div class="input-group"> 54 <input class="form-control" ng-model="actionText" /> 55 <span class="input-group-btn"> 56 <button class="btn btn-default" 57 ng-click="addNewItem(actionText)">Add</button> //add触发添加事件 参数为actionText 58 </span> 59 </div> 60 <table class="table table-striped"> 61 <thead> 62 <tr> 63 <th>Description</th> 64 <th>Done</th> 65 </tr> 66 </thead> 67 <tbody> 68 <tr ng-repeat="item in todo.items"> 69 <td>{{item.action}}</td> 70 <td><input type="checkbox" ng-model="item.done" /></td> 71 </tr> 72 </tbody> 73 </table> 74 </div> 75 </body> 76 </html>
Eg3:经过上面学习,应该摸清门路了,那么下面就很简单了
1 <!DOCTYPE html> 2 <html ng-app="todoApp"> 3 <head> 4 <title>TO DO List</title> 5 <link href="bootstrap.css" rel="stylesheet" /> 6 <link href="bootstrap-theme.css" rel="stylesheet" /> 7 <script src="angular.js"></script> 8 9 <script> 10 var model = { 11 user: "Adam" 12 }; 13 14 var todoApp = angular.module("todoApp", []); 15 //这里的$http相当于ajax服务 调用时用run 16 todoApp.run(function ($http) { 17 $http.get("todo.json").success(function (data) { 18 model.items = data; //从json文件中接收数据到model 19 }); 20 }); 21 22 todoApp.filter("checkedItems", function () { //这里定义了一个过滤器checkedItems 23 return function (items, showComplete) { 24 var resultArr = []; 25 angular.forEach(items, function (item) { 26 27 if (item.done == false || showComplete == true) { 28 resultArr.push(item); //item是未完成事项 或 showComplete == true时放入 29 } 30 }); 31 return resultArr; 32 } 33 }); 34 35 todoApp.controller("ToDoCtrl", function ($scope) { 36 $scope.todo = model; 37 38 $scope.incompleteCount = function () { 39 var count = 0; 40 angular.forEach($scope.todo.items, function (item) { 41 if (!item.done) { count++ } 42 }); 43 return count; 44 } 45 46 $scope.warningLevel = function () { 47 return $scope.incompleteCount() < 3 ? "label-success" : "label-warning"; 48 } 49 50 $scope.addNewItem = function(actionText) { 51 $scope.todo.items.push({ action: actionText, done: false}); 52 } 53 54 }); 55 </script> 56 57 58 </head> 59 <body ng-controller="ToDoCtrl"> 60 <div class="page-header"> 61 <h1> 62 {{todo.user}}'s To Do List 63 <span class="label label-default" ng-class="warningLevel()" 64 ng-hide="incompleteCount() == 0"> 65 {{incompleteCount()}} 66 </span> 67 </h1> 68 </div> 69 <div class="panel"> 70 <div class="input-group"> 71 <input class="form-control" ng-model="actionText" /> 72 <span class="input-group-btn"> 73 <button class="btn btn-default" 74 ng-click="addNewItem(actionText)">Add</button> 75 </span> 76 </div> 77 78 <table class="table table-striped"> 79 <thead> 80 <tr> 81 <th>Description</th> 82 <th>Done</th> 83 </tr> 84 </thead> 85 <tbody> 86 <tr ng-repeat= 87 "item in todo.items | checkedItems:showComplete | orderBy:'action'"> 88 <td>{{item.action}}</td> 89 <td><input type="checkbox" ng-model="item.done" /></td> 90 </tr> 91 </tbody> 92 </table> 93 94 <div class="checkbox-inline"> 95 <label><input type="checkbox" ng_model="showComplete"> Show Complete</label> //这里checkbox控制showcomplete的值 96 </div> 97 </div> 98 99 </body> 100 </html>
Eg4:发现js写在html里面不太好,有没有。。。
1 //productController.js 单独的定义module的js文件 2 angular.module("sportsStore") 3 .constant("productListActiveClass", "btn-primary") 4 .constant("productListPageCount", 3) 5 .controller("productListCtrl", function ($scope, $filter, 6 productListActiveClass, productListPageCount) { 7 8 var selectedCategory = null; 9 10 $scope.selectedPage = 1; 11 $scope.pageSize = productListPageCount; 12 13 $scope.selectCategory = function (newCategory) { 14 selectedCategory = newCategory; 15 $scope.selectedPage = 1; 16 } 17 18 $scope.selectPage = function (newPage) { 19 $scope.selectedPage = newPage; 20 } 21 22 $scope.categoryFilterFn = function (product) { 23 return selectedCategory == null || 24 product.category == selectedCategory; 25 } 26 27 $scope.getCategoryClass = function (category) { 28 return selectedCategory == category ? productListActiveClass : ""; 29 } 30 31 $scope.getPageClass = function (page) { 32 return $scope.selectedPage == page ? productListActiveClass : ""; 33 } 34 }); ---end 35 36 //sportsStore.js 注意与上面一样module是sportsStore controller名字不一样而已 37 angular.module("sportsStore") 38 .controller("sportsStoreCtrl", function ($scope) { 39 40 $scope.data = { 41 products: [ 42 { 43 name: "Product #1", description: "A product", 44 category: "Category #1", price: 100 45 }, 46 { 47 name: "Product #2", description: "A product", 48 category: "Category #1", price: 110 49 }, 50 { 51 name: "Product #3", description: "A product", 52 category: "Category #2", price: 210 53 }, 54 { 55 name: "Product #4", description: "A product", 56 category: "Category #3", price: 202 57 }] 58 }; 59 }); --end 60 61 //这里定义了一个过滤功能的模块 customerFilters 共有3个过滤实现 62 angular.module("customFilters", []) 63 .filter("unique", function () { //这里实现过滤重复属性值的功能 64 return function (data, propertyName) { 65 if (angular.isArray(data) && angular.isString(propertyName)) { 66 var results = []; 67 var keys = {}; 68 for (var i = 0; i < data.length; i++) { 69 var val = data[i][propertyName]; 70 if (angular.isUndefined(keys[val])) { 71 keys[val] = true; 72 results.push(val); 73 } 74 } 75 return results; 76 } else { 77 return data; 78 } 79 } 80 }) 81 .filter("range", function ($filter) { //实现了选择页数功能 82 return function (data, page, size) { 83 if (angular.isArray(data) && angular.isNumber(page) && angular.isNumber(size)) { 84 var start_index = (page - 1) * size; 85 if (data.length < start_index) { 86 return []; 87 } else { 88 return $filter("limitTo")(data.splice(start_index), size); 89 } 90 } else { 91 return data; 92 } 93 } 94 }) 95 .filter("pageCount", function () { //统计页数 96 return function (data, size) { 97 if (angular.isArray(data)) { 98 var result = []; 99 for (var i = 0; i < Math.ceil(data.length / size) ; i++) { //这样总能取到真是页数 100 result.push(i); 101 } 102 return result; 103 } else { 104 return data; 105 } 106 } 107 }); -- end 108 109 <html ng-app="sportsStore"> 110 <head> 111 <title>SportsStore</title> 112 <script> 113 angular.module("sportsStore", ["customFilters"]); //customFilters是依赖模块 114 </script> 115 <script src="controllers/sportsStore.js"></script> 116 <script src="filters/customFilters.js"></script> 117 <script src="controllers/productListControllers.js"></script> 118 </head> 119 <body ng-controller="sportsStoreCtrl"> 120 <div class="navbar navbar-inverse"> 121 <a class="navbar-brand" href="#">SPORTS STORE</a> 122 </div> 123 <div class="panel panel-default row" ng-controller="productListCtrl"> 124 <div class="col-xs-3"> 125 <a ng-click="selectCategory()" 126 class="btn btn-block btn-default btn-lg">Home</a> 127 <a ng-repeat="item in data.products | orderBy:'category' | unique:'category'" //种类不允许重复 128 ng-click="selectCategory(item)" class=" btn btn-block btn-default btn-lg" 129 ng-class="getCategoryClass(item)"> 130 {{item}} 131 </a> 132 </div> 133 <div class="col-xs-8"> 134 <div class="well" 135 ng-repeat="item in data.products | filter:categoryFilterFn | range:selectedPage:pageSize"> //这里比较难理解的是自定义filter和默认filter的区别 136 <h3> 137 <strong>{{item.name}}</strong> 138 <span class="pull-right label label-primary"> 139 {{item.price | currency}} //currency是angular自带美元过滤器 140 </span> 141 </h3> 142 <span class="lead">{{item.description}}</span> 143 </div> 144 <div class="pull-right btn-group"> 145 <a ng-repeat="page in data.products | filter:categoryFilterFn | pageCount:pageSize" //分页的显示 146 ng-click="selectPage($index + 1)" class="btn btn-default" 147 ng-class="getPageClass($index + 1)"> //默认的selectedPage==1 所以看是的时候1高亮显示 148 {{$index + 1}} 149 </a> 150 </div> 151 </div> 152 </body> 153 </html>
Eg5:怎么样,看过瘾没?好像这里东西挺多的呀,继续搞起。。。
1 //cart.js 购物车的js文件 2 angular.module("cart", []) 3 .factory("cart", function () { 4 5 var cartData = []; 6 7 return { 8 //添加物品 要判断是否添加的是相同id的物品 9 addProduct: function (id, name, price) { 10 var addedToExistingItem = false; 11 for (var i = 0; i < cartData.length; i++) { 12 if (cartData[i].id == id) { 13 cartData[i].count++; 14 addedToExistingItem = true; 15 break; 16 } 17 } 18 if (!addedToExistingItem) { 19 cartData.push({ 20 count: 1, id: id, price: price, name: name 21 }); 22 } 23 }, 24 //移除产品 25 removeProduct: function (id) { 26 for (var i = 0; i < cartData.length; i++) { 27 if (cartData[i].id == id) { 28 cartData.splice(i, 1); 29 break; 30 } 31 } 32 }, 33 34 getProducts: function () { 35 return cartData; 36 } 37 } 38 }) 39 .directive("cartSummary", function (cart) { //这是指令 大家可以看我之前的博客 40 return { 41 restrict: "E", 42 templateUrl: "components/cart/cartSummary.html", //该网页可用controller下的函数 43 controller: function ($scope) { 44 45 var cartData = cart.getProducts(); //调用服务 46 //计算总价 47 $scope.total = function () { 48 var total = 0; 49 for (var i = 0; i < cartData.length; i++) { 50 total += (cartData[i].price * cartData[i].count); 51 } 52 return total; 53 } 54 55 $scope.itemCount = function () { 56 var total = 0; 57 for (var i = 0; i < cartData.length; i++) { 58 total += cartData[i].count; 59 } 60 return total; 61 } 62 } 63 }; 64 });
1 //cartSummary.html 2 <style> 3 .navbar-right { float: right !important; margin-right: 5px; } 4 .navbar-text { margin-right: 10px; } 5 </style> 6 7 <div class="navbar-right"> 8 <div class="navbar-text"> 9 <b>Your cart:</b> 10 {{itemCount()}} item(s), 11 {{total() | currency}} 12 </div> 13 <a href="#/checkout" class="btn btn-default navbar-btn">Checkout</a> 14 </div> 15 16 //checkoutController.js 17 angular.module("sportsStore") 18 .controller("cartSummaryController", function ($scope, cart) { 19 20 $scope.cartData = cart.getProducts(); 21 22 $scope.total = function () { 23 var total = 0; 24 for (var i = 0; i < $scope.cartData.length; i++) { 25 total += ($scope.cartData[i].price * $scope.cartData[i].count); 26 } 27 return total; 28 } 29 30 $scope.remove = function (id) { 31 cart.removeProduct(id); 32 } 33 });
看到这里是不是觉得angularJs有点不可思议。。。下面可以看下由路由控制的单页面应用是如何实现的。
1 //app.html 2 <!DOCTYPE html> 3 <html ng-app="sportsStore"> 4 <head> 5 <title>SportsStore</title> 6 <script> 7 angular.module("sportsStore", ["customFilters", "cart", "ngRoute"]) //引进所依赖的模块 ngRoute是路由 8 .config(function ($routeProvider) { 9 10 $routeProvider.when("/complete", { 11 templateUrl: "/views/thankYou.html" 12 }); 13 14 $routeProvider.when("/placeorder", { 15 templateUrl: "/views/placeOrder.html" 16 }); 17 18 $routeProvider.when("/checkout", { 19 templateUrl: "/views/checkoutSummary.html" 20 }); 21 22 $routeProvider.when("/products", { 23 templateUrl: "/views/productList.html" 24 }); 25 26 $routeProvider.otherwise({ //默认失去产品详细页面 27 templateUrl: "/views/productList.html" 28 }); 29 }); 30 </script> 31 <script src="controllers/sportsStore.js"></script> 32 <script src="filters/customFilters.js"></script> 33 <script src="controllers/productListControllers.js"></script> 34 <script src="components/cart/cart.js"></script> 35 <script src="ngmodules/angular-route.js"></script> 36 <script src="controllers/checkoutControllers.js"></script> 37 </head> 38 <body ng-controller="sportsStoreCtrl"> 39 <div class="navbar navbar-inverse"> 40 <a class="navbar-brand" href="#">SPORTS STORE</a> 41 <cart-summary /> 42 </div> 43 <div class="alert alert-danger" ng-show="data.error"> 44 Error ({{data.error.status}}). The product data was not loaded. 45 <a href="/app.html" class="alert-link">Click here to try again</a> 46 </div> 47 <ng-view /> 48 </body> 49 </html> 50 51 //checkoutSummary.html 52 <h2>Your cart</h2> 53 54 <div ng-controller="cartSummaryController"> 55 56 <div class="alert alert-warning" ng-show="cartData.length == 0"> 57 There are no products in your shopping cart. 58 <a href="#/products" class="alert-link">Click here to return to the catalogue</a> //前往productList页面 59 </div> 60 61 <div ng-hide="cartData.length == 0"> 62 <table class="table"> 63 <thead> 64 <tr> 65 <th>Quantity</th> 66 <th>Item</th> 67 <th class="text-right">Price</th> 68 <th class="text-right">Subtotal</th> 69 </tr> 70 </thead> 71 <tbody> 72 <tr ng-repeat="item in cartData"> 73 <td class="text-center">{{item.count}}</td> 74 <td class="text-left">{{item.name}}</td> 75 <td class="text-right">{{item.price | currency}}</td> 76 <td class="text-right">{{ (item.price * item.count) | currency}}</td> 77 <td> 78 <button ng-click="remove(item.id)" 79 class="btn btn-sm btn-warning"> 80 Remove 81 </button> 82 </td> 83 </tr> 84 </tbody> 85 <tfoot> 86 <tr> 87 <td colspan="3" class="text-right">Total:</td> 88 <td class="text-right"> 89 {{total() | currency}} 90 </td> 91 </tr> 92 </tfoot> 93 </table> 94 95 <div class="text-center"> 96 <a class="btn btn-primary" href="#/products">Continue shopping</a> 97 <a class="btn btn-primary" href="#/placeorder">Place order now</a> 98 </div> 99 </div> 100 </div> 101 102 //productList.html 103 <div class="panel panel-default row" ng-controller="productListCtrl" 104 ng-hide="data.error"> 105 <div class="col-xs-3"> 106 <a ng-click="selectCategory()" 107 class="btn btn-block btn-default btn-lg">Home</a> 108 <a ng-repeat="item in data.products | orderBy:'category' | unique:'category'" 109 ng-click="selectCategory(item)" class=" btn btn-block btn-default btn-lg" 110 ng-class="getCategoryClass(item)"> 111 {{item}} 112 </a> 113 </div> 114 <div class="col-xs-8"> 115 <div class="well" 116 ng-repeat="item in data.products | filter:categoryFilterFn | range:selectedPage:pageSize"> 117 <h3> 118 <strong>{{item.name}}</strong> 119 <span class="pull-right label label-primary"> 120 {{item.price | currency}} 121 </span> 122 </h3> 123 <button ng-click="addProductToCart(item)" 124 class="btn btn-success pull-right"> 125 Add to cart 126 </button> 127 <span class="lead">{{item.description}}</span> 128 </div> 129 <div class="pull-right btn-group"> 130 <a ng-repeat="page in data.products | filter:categoryFilterFn | pageCount:pageSize" 131 ng-click="selectPage($index + 1)" class="btn btn-default" 132 ng-class="getPageClass($index + 1)"> 133 {{$index + 1}} 134 </a> 135 </div> 136 </div> 137 </div>
这上面主要是把service,directive和路由结合在一起了,如果搞懂了可以自己做一个页面。
还想看吗 最后再来一个登陆验证的吧!!
1 //adminController.js 控制用户登录 2 angular.module("sportsStoreAdmin") 3 .constant("authUrl", "http://localhost:5500/users/login") 4 .constant("ordersUrl", "http://localhost:5500/orders") 5 .controller("authCtrl", function ($scope, $http, $location, authUrl) { 6 7 $scope.authenticate = function (user, pass) { //验证用户名和密码 8 $http.post(authUrl, { //发送请求 9 username: user, 10 password: pass 11 }, { 12 withCredentials: true 13 }).success(function (data) { 14 $location.path("/main"); 15 }).error(function (error) { 16 $scope.authenticationError = error; 17 }); 18 } 19 }) 20 .controller("mainCtrl", function ($scope) { 21 22 $scope.screens = ["Products", "Orders"]; 23 $scope.current = $scope.screens[0]; 24 25 $scope.setScreen = function (index) { 26 $scope.current = $scope.screens[index]; 27 }; 28 29 $scope.getScreen = function () { 30 return $scope.current == "Products" 31 ? "/views/adminProducts.html" : "/views/adminOrders.html"; 32 }; 33 }) 34 .controller("ordersCtrl", function ($scope, $http, ordersUrl) { 35 36 $http.get(ordersUrl, { withCredentials: true }) 37 .success(function (data) { 38 $scope.orders = data; 39 }) 40 .error(function (error) { 41 $scope.error = error; 42 }); 43 44 $scope.selectedOrder; 45 46 $scope.selectOrder = function (order) { 47 $scope.selectedOrder = order; 48 }; 49 50 $scope.calcTotal = function (order) { 51 var total = 0; 52 for (var i = 0; i < order.products.length; i++) { 53 total += 54 order.products[i].count * order.products[i].price; 55 } 56 return total; 57 } 58 }); 59 //admin.login.html 登录页面 60 <div class="well" ng-controller="authCtrl"> 61 62 <div class="alert alert-info" ng-hide="authenticationError"> 63 Enter your username and password and click Log In to authenticate 64 </div> 65 66 <div class="alert alert-danger" ng-show="authenticationError"> 67 Authentication Failed ({{authenticationError.status}}). Try again. 68 </div> 69 70 <form name="authForm" novalidate> 71 <div class="form-group"> 72 <label>Username</label> 73 <input name="username" class="form-control" ng-model="username" required /> 74 </div> 75 <div class="form-group"> 76 <label>Password</label> 77 <input name="password" type="password" class="form-control" 78 ng-model="password" required /> 79 </div> 80 <div class="text-center"> 81 <button ng-click="authenticate(username, password)" 82 ng-disabled="authForm.$invalid" 83 class="btn btn-primary"> 84 Log In 85 </button> 86 </div> 87 </form> 88 </div> 89 90 <html ng-app="sportsStoreAdmin"> 91 <head> 92 <title>Administration</title> 93 <script src="angular.js"></script> 94 <script src="ngmodules/angular-route.js"></script> 95 <script src="ngmodules/angular-resource.js"></script> 96 <link href="bootstrap.css" rel="stylesheet" /> 97 <link href="bootstrap-theme.css" rel="stylesheet" /> 98 <script> 99 angular.module("sportsStoreAdmin", ["ngRoute", "ngResource"]) 100 .config(function ($routeProvider) { 101 102 $routeProvider.when("/login", { 103 templateUrl: "/views/adminLogin.html" 104 }); 105 106 $routeProvider.when("/main", { 107 templateUrl: "/views/adminMain.html" 108 }); 109 110 $routeProvider.otherwise({ 111 redirectTo: "/login" 112 }); 113 }); 114 </script> 115 <script src="controllers/adminControllers.js"></script> 116 <script src="controllers/adminProductController.js"></script> 117 </head> 118 <body> 119 <ng-view /> 120 </body> 121 </html>
好了,今天就这么多大家好好消化,我也要多看下子。。。
---恢复内容结束---