angularJs案例汇总
---恢复内容开始---
这里我会把学习过程中碰到的demo与大家分享,由浅入深,逐个分析。
Eg1:入门必备
<html ng-app="todoApp">
<head>
<title>TO DO List</title>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
<script src="angular.js"></script>
<script>
//数据模型
var model = {
user: "Adam",
items: [{ action: "Buy Flowers", done: false },
{ action: "Get Shoes", done: false },
{ action: "Collect Tickets", done: true },
{ action: "Call Joe", done: false }]
};
//定义全局的module []表示不引用其他module
var todoApp = angular.module("todoApp", []);
//module里面可以定义多个controller 拥有各自的$scope
todoApp.controller("ToDoCtrl", function ($scope) {
$scope.todo = model;
}); </script>
</head> <body ng-controller="ToDoCtrl">
<div class="page-header">
<h1>
{{todo.user}}'s To Do List
<span class="label label-default">{{todo.items.length}}</span>
</h1>
</div>
<div class="panel">
<div class="input-group">
<input class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default">Add</button>
</span>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Description</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in todo.items"> //常见指令
<td>{{item.action}}</td> <td><input type="checkbox" ng-model="item.done" /></td> //实现双向数据绑定
<td>{{item.done}}</td>
</tr>
</tbody>
</table>
</div>
</body> </html>
我们可以看到angularJs很适合和bootstrap一起运用,他并不依赖其他类库。
Eg2:稍微有些复杂,对于刚学的同学
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>TO DO List</title>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
<script src="angular.js"></script>
<script> var model = {
user: "Adam",
items: [{ action: "Buy Flowers", done: false },
{ action: "Get Shoes", done: false },
{ action: "Collect Tickets", done: true },
{ action: "Call Joe", done: false }]
}; var todoApp = angular.module("todoApp", []); todoApp.controller("ToDoCtrl", function ($scope) {
$scope.todo = model;
//在该scope下定义函数 计算未完成的count
$scope.incompleteCount = function () {
var count = 0;
angular.forEach($scope.todo.items, function (item) {
if (!item.done) { count++ }
});
return count;
} $scope.warningLevel = function () {
return $scope.incompleteCount() < 3 ? "label-success" : "label-warning"; //count<3 className="label-success"
}
//该函数用于添加新事项
$scope.addNewItem = function (actionText) {
$scope.todo.items.push({ action: actionText, done: false });
}
}); </script>
</head>
<body ng-controller="ToDoCtrl">
<div class="page-header">
<h1>
{{todo.user}}'s To Do List
<span class="label label-default" ng-class="warningLevel()" //angularJs指令 用于确定该元素class
ng-hide="incompleteCount() == 0"> //如果为0 则hide
{{incompleteCount()}}
</span>
</h1>
</div>
<div class="panel">
<div class="input-group">
<input class="form-control" ng-model="actionText" />
<span class="input-group-btn">
<button class="btn btn-default"
ng-click="addNewItem(actionText)">Add</button> //add触发添加事件 参数为actionText
</span>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Description</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in todo.items">
<td>{{item.action}}</td>
<td><input type="checkbox" ng-model="item.done" /></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Eg3:经过上面学习,应该摸清门路了,那么下面就很简单了
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>TO DO List</title>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
<script src="angular.js"></script> <script>
var model = {
user: "Adam"
}; var todoApp = angular.module("todoApp", []);
//这里的$http相当于ajax服务 调用时用run
todoApp.run(function ($http) {
$http.get("todo.json").success(function (data) {
model.items = data; //从json文件中接收数据到model
});
}); todoApp.filter("checkedItems", function () { //这里定义了一个过滤器checkedItems
return function (items, showComplete) {
var resultArr = [];
angular.forEach(items, function (item) { if (item.done == false || showComplete == true) {
28 resultArr.push(item); //item是未完成事项 或 showComplete == true时放入
29 }
});
return resultArr;
}
}); todoApp.controller("ToDoCtrl", function ($scope) {
$scope.todo = model; $scope.incompleteCount = function () {
var count = 0;
angular.forEach($scope.todo.items, function (item) {
if (!item.done) { count++ }
});
return count;
} $scope.warningLevel = function () {
return $scope.incompleteCount() < 3 ? "label-success" : "label-warning";
} $scope.addNewItem = function(actionText) {
$scope.todo.items.push({ action: actionText, done: false});
} });
</script> </head>
<body ng-controller="ToDoCtrl">
<div class="page-header">
<h1>
{{todo.user}}'s To Do List
<span class="label label-default" ng-class="warningLevel()"
ng-hide="incompleteCount() == 0">
{{incompleteCount()}}
</span>
</h1>
</div>
<div class="panel">
<div class="input-group">
<input class="form-control" ng-model="actionText" />
<span class="input-group-btn">
<button class="btn btn-default"
ng-click="addNewItem(actionText)">Add</button>
</span>
</div> <table class="table table-striped">
<thead>
<tr>
<th>Description</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<tr ng-repeat=
"item in todo.items | checkedItems:showComplete | orderBy:'action'">
<td>{{item.action}}</td>
<td><input type="checkbox" ng-model="item.done" /></td>
</tr>
</tbody>
</table> <div class="checkbox-inline">
<label><input type="checkbox" ng_model="showComplete"> Show Complete</label> //这里checkbox控制showcomplete的值
</div>
</div> </body>
</html>
Eg4:发现js写在html里面不太好,有没有。。。
//productController.js 单独的定义module的js文件
angular.module("sportsStore")
.constant("productListActiveClass", "btn-primary")
.constant("productListPageCount", 3)
.controller("productListCtrl", function ($scope, $filter,
productListActiveClass, productListPageCount) { var selectedCategory = null; $scope.selectedPage = 1;
$scope.pageSize = productListPageCount; $scope.selectCategory = function (newCategory) {
selectedCategory = newCategory;
$scope.selectedPage = 1;
} $scope.selectPage = function (newPage) {
$scope.selectedPage = newPage;
} $scope.categoryFilterFn = function (product) {
return selectedCategory == null ||
product.category == selectedCategory;
} $scope.getCategoryClass = function (category) {
return selectedCategory == category ? productListActiveClass : "";
} $scope.getPageClass = function (page) {
return $scope.selectedPage == page ? productListActiveClass : "";
}
}); ---end //sportsStore.js 注意与上面一样module是sportsStore controller名字不一样而已
angular.module("sportsStore")
.controller("sportsStoreCtrl", function ($scope) { $scope.data = {
products: [
{
name: "Product #1", description: "A product",
category: "Category #1", price: 100
},
{
name: "Product #2", description: "A product",
category: "Category #1", price: 110
},
{
name: "Product #3", description: "A product",
category: "Category #2", price: 210
},
{
name: "Product #4", description: "A product",
category: "Category #3", price: 202
}]
};
}); --end //这里定义了一个过滤功能的模块 customerFilters 共有3个过滤实现
angular.module("customFilters", [])
.filter("unique", function () { //这里实现过滤重复属性值的功能
return function (data, propertyName) {
if (angular.isArray(data) && angular.isString(propertyName)) {
var results = [];
var keys = {};
for (var i = 0; i < data.length; i++) {
var val = data[i][propertyName];
if (angular.isUndefined(keys[val])) {
keys[val] = true;
results.push(val);
}
}
return results;
} else {
return data;
}
}
})
.filter("range", function ($filter) { //实现了选择页数功能
return function (data, page, size) {
if (angular.isArray(data) && angular.isNumber(page) && angular.isNumber(size)) {
var start_index = (page - 1) * size;
if (data.length < start_index) {
return [];
} else {
return $filter("limitTo")(data.splice(start_index), size);
}
} else {
return data;
}
}
})
.filter("pageCount", function () { //统计页数
return function (data, size) {
if (angular.isArray(data)) {
var result = [];
for (var i = 0; i < Math.ceil(data.length / size) ; i++) { //这样总能取到真是页数
result.push(i);
}
return result;
} else {
return data;
}
}
}); -- end <html ng-app="sportsStore">
<head>
<title>SportsStore</title>
<script>
angular.module("sportsStore", ["customFilters"]); //customFilters是依赖模块
</script>
<script src="controllers/sportsStore.js"></script>
<script src="filters/customFilters.js"></script>
<script src="controllers/productListControllers.js"></script>
</head>
<body ng-controller="sportsStoreCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">SPORTS STORE</a>
</div>
<div class="panel panel-default row" ng-controller="productListCtrl">
<div class="col-xs-3">
<a ng-click="selectCategory()"
class="btn btn-block btn-default btn-lg">Home</a>
<a ng-repeat="item in data.products | orderBy:'category' | unique:'category'" //种类不允许重复
ng-click="selectCategory(item)" class=" btn btn-block btn-default btn-lg"
ng-class="getCategoryClass(item)">
{{item}}
</a>
</div>
<div class="col-xs-8">
<div class="well"
ng-repeat="item in data.products | filter:categoryFilterFn | range:selectedPage:pageSize"> //这里比较难理解的是自定义filter和默认filter的区别
<h3>
<strong>{{item.name}}</strong>
<span class="pull-right label label-primary">
{{item.price | currency}} //currency是angular自带美元过滤器
</span>
</h3>
<span class="lead">{{item.description}}</span>
</div>
<div class="pull-right btn-group">
<a ng-repeat="page in data.products | filter:categoryFilterFn | pageCount:pageSize" //分页的显示
ng-click="selectPage($index + 1)" class="btn btn-default"
ng-class="getPageClass($index + 1)"> //默认的selectedPage==1 所以看是的时候1高亮显示
{{$index + 1}}
</a>
</div>
</div>
</body>
</html>
Eg5:怎么样,看过瘾没?好像这里东西挺多的呀,继续搞起。。。
//cart.js 购物车的js文件
angular.module("cart", [])
.factory("cart", function () { var cartData = []; return {
//添加物品 要判断是否添加的是相同id的物品
addProduct: function (id, name, price) {
var addedToExistingItem = false;
for (var i = 0; i < cartData.length; i++) {
if (cartData[i].id == id) {
cartData[i].count++;
addedToExistingItem = true;
break;
}
}
if (!addedToExistingItem) {
cartData.push({
count: 1, id: id, price: price, name: name
});
}
},
//移除产品
removeProduct: function (id) {
for (var i = 0; i < cartData.length; i++) {
if (cartData[i].id == id) {
cartData.splice(i, 1);
break;
}
}
}, getProducts: function () {
return cartData;
}
}
})
.directive("cartSummary", function (cart) { //这是指令 大家可以看我之前的博客
return {
restrict: "E",
templateUrl: "components/cart/cartSummary.html", //该网页可用controller下的函数
controller: function ($scope) { var cartData = cart.getProducts(); //调用服务
//计算总价
$scope.total = function () {
var total = 0;
for (var i = 0; i < cartData.length; i++) {
total += (cartData[i].price * cartData[i].count);
}
return total;
} $scope.itemCount = function () {
var total = 0;
for (var i = 0; i < cartData.length; i++) {
total += cartData[i].count;
}
return total;
}
}
};
});
//cartSummary.html
<style>
.navbar-right { float: right !important; margin-right: 5px; }
.navbar-text { margin-right: 10px; }
</style> <div class="navbar-right">
<div class="navbar-text">
<b>Your cart:</b>
{{itemCount()}} item(s),
{{total() | currency}}
</div>
<a href="#/checkout" class="btn btn-default navbar-btn">Checkout</a>
</div> //checkoutController.js
angular.module("sportsStore")
.controller("cartSummaryController", function ($scope, cart) { $scope.cartData = cart.getProducts();
$scope.total = function () {
var total = 0;
for (var i = 0; i < $scope.cartData.length; i++) {
total += ($scope.cartData[i].price * $scope.cartData[i].count);
}
return total;
} $scope.remove = function (id) {
cart.removeProduct(id);
}
});
看到这里是不是觉得angularJs有点不可思议。。。下面可以看下由路由控制的单页面应用是如何实现的。
//app.html
<!DOCTYPE html>
<html ng-app="sportsStore">
<head>
<title>SportsStore</title>
<script>
angular.module("sportsStore", ["customFilters", "cart", "ngRoute"]) //引进所依赖的模块 ngRoute是路由
.config(function ($routeProvider) { $routeProvider.when("/complete", {
templateUrl: "/views/thankYou.html"
}); $routeProvider.when("/placeorder", {
templateUrl: "/views/placeOrder.html"
}); $routeProvider.when("/checkout", {
templateUrl: "/views/checkoutSummary.html"
}); $routeProvider.when("/products", {
templateUrl: "/views/productList.html"
}); $routeProvider.otherwise({ //默认失去产品详细页面
templateUrl: "/views/productList.html"
});
});
</script>
<script src="controllers/sportsStore.js"></script>
<script src="filters/customFilters.js"></script>
<script src="controllers/productListControllers.js"></script>
<script src="components/cart/cart.js"></script>
<script src="ngmodules/angular-route.js"></script>
<script src="controllers/checkoutControllers.js"></script>
</head>
<body ng-controller="sportsStoreCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">SPORTS STORE</a>
<cart-summary />
</div>
<div class="alert alert-danger" ng-show="data.error">
Error ({{data.error.status}}). The product data was not loaded.
<a href="/app.html" class="alert-link">Click here to try again</a>
</div>
<ng-view />
</body>
</html> //checkoutSummary.html
<h2>Your cart</h2> <div ng-controller="cartSummaryController"> <div class="alert alert-warning" ng-show="cartData.length == 0">
There are no products in your shopping cart.
<a href="#/products" class="alert-link">Click here to return to the catalogue</a> //前往productList页面
</div> <div ng-hide="cartData.length == 0">
<table class="table">
<thead>
<tr>
<th>Quantity</th>
<th>Item</th>
<th class="text-right">Price</th>
<th class="text-right">Subtotal</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in cartData">
<td class="text-center">{{item.count}}</td>
<td class="text-left">{{item.name}}</td>
<td class="text-right">{{item.price | currency}}</td>
<td class="text-right">{{ (item.price * item.count) | currency}}</td>
<td>
<button ng-click="remove(item.id)"
class="btn btn-sm btn-warning">
Remove
</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3" class="text-right">Total:</td>
<td class="text-right">
{{total() | currency}}
</td>
</tr>
</tfoot>
</table> <div class="text-center">
<a class="btn btn-primary" href="#/products">Continue shopping</a>
<a class="btn btn-primary" href="#/placeorder">Place order now</a>
</div>
</div>
</div> //productList.html
<div class="panel panel-default row" ng-controller="productListCtrl"
ng-hide="data.error">
<div class="col-xs-3">
<a ng-click="selectCategory()"
class="btn btn-block btn-default btn-lg">Home</a>
<a ng-repeat="item in data.products | orderBy:'category' | unique:'category'"
ng-click="selectCategory(item)" class=" btn btn-block btn-default btn-lg"
ng-class="getCategoryClass(item)">
{{item}}
</a>
</div>
<div class="col-xs-8">
<div class="well"
ng-repeat="item in data.products | filter:categoryFilterFn | range:selectedPage:pageSize">
<h3>
<strong>{{item.name}}</strong>
<span class="pull-right label label-primary">
{{item.price | currency}}
</span>
</h3>
<button ng-click="addProductToCart(item)"
class="btn btn-success pull-right">
Add to cart
</button>
<span class="lead">{{item.description}}</span>
</div>
<div class="pull-right btn-group">
<a ng-repeat="page in data.products | filter:categoryFilterFn | pageCount:pageSize"
ng-click="selectPage($index + 1)" class="btn btn-default"
ng-class="getPageClass($index + 1)">
{{$index + 1}}
</a>
</div>
</div>
</div>
这上面主要是把service,directive和路由结合在一起了,如果搞懂了可以自己做一个页面。
还想看吗 最后再来一个登陆验证的吧!!
//adminController.js 控制用户登录
angular.module("sportsStoreAdmin")
.constant("authUrl", "http://localhost:5500/users/login")
.constant("ordersUrl", "http://localhost:5500/orders")
.controller("authCtrl", function ($scope, $http, $location, authUrl) { $scope.authenticate = function (user, pass) { //验证用户名和密码
$http.post(authUrl, { //发送请求
username: user,
password: pass
}, {
withCredentials: true
}).success(function (data) {
$location.path("/main");
}).error(function (error) {
$scope.authenticationError = error;
});
}
})
.controller("mainCtrl", function ($scope) { $scope.screens = ["Products", "Orders"];
$scope.current = $scope.screens[0]; $scope.setScreen = function (index) {
$scope.current = $scope.screens[index];
}; $scope.getScreen = function () {
return $scope.current == "Products"
? "/views/adminProducts.html" : "/views/adminOrders.html";
};
})
.controller("ordersCtrl", function ($scope, $http, ordersUrl) { $http.get(ordersUrl, { withCredentials: true })
.success(function (data) {
$scope.orders = data;
})
.error(function (error) {
$scope.error = error;
}); $scope.selectedOrder; $scope.selectOrder = function (order) {
$scope.selectedOrder = order;
}; $scope.calcTotal = function (order) {
var total = 0;
for (var i = 0; i < order.products.length; i++) {
total +=
order.products[i].count * order.products[i].price;
}
return total;
}
});
//admin.login.html 登录页面
<div class="well" ng-controller="authCtrl"> <div class="alert alert-info" ng-hide="authenticationError">
Enter your username and password and click Log In to authenticate
</div> <div class="alert alert-danger" ng-show="authenticationError">
Authentication Failed ({{authenticationError.status}}). Try again.
</div> <form name="authForm" novalidate>
<div class="form-group">
<label>Username</label>
<input name="username" class="form-control" ng-model="username" required />
</div>
<div class="form-group">
<label>Password</label>
<input name="password" type="password" class="form-control"
ng-model="password" required />
</div>
<div class="text-center">
<button ng-click="authenticate(username, password)"
ng-disabled="authForm.$invalid"
class="btn btn-primary">
Log In
</button>
</div>
</form>
</div> <html ng-app="sportsStoreAdmin">
<head>
<title>Administration</title>
<script src="angular.js"></script>
<script src="ngmodules/angular-route.js"></script>
<script src="ngmodules/angular-resource.js"></script>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
<script>
angular.module("sportsStoreAdmin", ["ngRoute", "ngResource"])
.config(function ($routeProvider) { $routeProvider.when("/login", {
templateUrl: "/views/adminLogin.html"
}); $routeProvider.when("/main", {
templateUrl: "/views/adminMain.html"
}); $routeProvider.otherwise({
redirectTo: "/login"
});
});
</script>
<script src="controllers/adminControllers.js"></script>
<script src="controllers/adminProductController.js"></script>
</head>
<body>
<ng-view />
</body>
</html>
好了,今天就这么多大家好好消化,我也要多看下子。。。
---恢复内容结束---
angularJs案例汇总的更多相关文章
- Flex外包公司——案例汇总
Flex做的案例汇总: http://flex.org/showcase/ http://taggraph.com/everybody http://demoprod.informationbuild ...
- ES业界优秀实践案例汇总
ES业界优秀案例汇总 携程 LinkedIn Etsy国外电商CPU(vCore) 70*32 1000*12 4200单日索引数据条数 600亿 500亿 100亿单核处理数据性能/天 2600万/ ...
- Vue-CLI项目路由案例汇总
0901自我总结 Vue-CLI项目路由案例汇总 router.js import Vue from 'vue' import Router from 'vue-router' import Cour ...
- 中国爬虫违法违规案例汇总github项目介绍
中国爬虫违法违规案例汇总github项目介绍 GitHub - 本项目用来整理所有中国大陆爬虫开发者涉诉与违规相关的新闻.资料与法律法规.致力于帮助在中国大陆工作的爬虫行业从业者了解我国相关法律,避免 ...
- mysql 案例 ~ 常见案例汇总
一 简介:这里汇总了一些mysql常见的问题二 案例场景 问题1 mysql设置了默认慢日志记录1S,为何会记录不超过1S的sql语句 答案 mysql~log_queries_not_usi ...
- mysql 查询优化案例汇总
一 简介:此文章为经历过的sql案例集合和相关思路 二 案例1: 现象: 测试环境出现select语句,join2张表多次join,explain结果如下 出现 using where,using j ...
- Openresty最佳案例 | 汇总
转载请标明出处: http://blog.csdn.net/forezp/article/details/78616856 本文出自方志朋的博客 目录 Openresty最佳案例 | 第1篇:Ngin ...
- angularJS常见问题汇总
问题描述 解决方案 当你简单的动态给页面插入html时, 此时html带有angular的语法不会执行的. var uploadInfo = '上传成功!<a ng-click="qu ...
- AngularJS - 常用方法汇总
1. 数组元素的常用方法: http://www.cnblogs.com/diaosizhang/p/3729078.html 2. js的强大的splice方法 http://www.jb51.n ...
随机推荐
- 【Win10 UWP】URI Scheme(二):自定义协议的处理和适用场景
上一篇提到Windows Store协议的使用,其实Windows Store协议仅是系统内建的一种协议规则.我们也可以自己定义一套规范的URI-Scheme,除了可以给其他App调用外,本应用也可以 ...
- Snmp协议应用-扫描局域网内打印机
.h2cls { background: #6fa833 none repeat scroll 0 0 !important; color: #fff; font-family: "微软雅黑 ...
- Oracle expdp/impdp导出导入命令及数据库备份
使用EXPDP和IMPDP时应该注意的事项: EXP和IMP是客户端工具程序,它们既可以在客户端使用,也可以在服务端使用. EXPDP和IMPDP是服务端的工具程序,他们只能在ORACLE服务端使用, ...
- 即时通信系统中如何实现:全局系统通知,并与Web后台集成?【低调赠送:QQ高仿版GGTalk 5.1 最新源码】
像QQ这样的即时通信软件,时不时就会从桌面的右下角弹出一个小窗口,或是显示一个广告.或是一个新闻.或是一个公告等.在这里,我们将其统称为“全局系统通知”.很多使用GGTalk的朋友都建议我加上一个类似 ...
- Unity3D入门之Unity3D介绍以及编辑器的使用(1)
1.Unity3D介绍 Unity3D是跨平台(IOS.Android.Windows Phone.Windows.Flash.XBOX360.PS3.Wii等)游戏引擎,可以开发2D.2.5D.3D ...
- python sorted排序
python sorted排序 Python不仅提供了list.sort()方法来实现列表的排序,而且提供了内建sorted()函数来实现对复杂列表的排序以及按照字典的key和value进行排序. s ...
- [php入门] 2、基础核心语法大纲
1 前言 最近在学PHP,上节主要总结了PHP开发环境搭建<[php入门] 1.从安装开发环境环境到(庄B)做个炫酷的登陆应用>.本节主要总结PHP的核心基础语法,基本以粗轮廓写,可以算作 ...
- 深入CSS,让网页开发少点“坑”
通常我们在学习CSS的时候,感觉语法很容易掌握,实际应用中却碰到各式各样难以填补的“坑”,为避免大家受到同样的困惑与不解,本文详细讲解了CSS中优先级和Stacking Context等高级特性.让你 ...
- Java-条件语句、循环语句练习
题目一:一张纸的厚度大约是0.08mm,对折多少次之后能达到珠穆朗玛峰的高度(8848.13米)? double height=0.08; for(int i=1;i>0;i++) { heig ...
- .NetCore~Linux环境下部署
NetCore正式版已经出现有段时候了,Windows下使用vs2015开发.netCore应用程序,然后通过dotnet程序开启WEB服务,用着很像node.js,当然我们不会于只局限于window ...