---恢复内容开始---

这里我会把学习过程中碰到的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案例汇总的更多相关文章

  1. Flex外包公司——案例汇总

    Flex做的案例汇总: http://flex.org/showcase/ http://taggraph.com/everybody http://demoprod.informationbuild ...

  2. ES业界优秀实践案例汇总

    ES业界优秀案例汇总 携程 LinkedIn Etsy国外电商CPU(vCore) 70*32 1000*12 4200单日索引数据条数 600亿 500亿 100亿单核处理数据性能/天 2600万/ ...

  3. Vue-CLI项目路由案例汇总

    0901自我总结 Vue-CLI项目路由案例汇总 router.js import Vue from 'vue' import Router from 'vue-router' import Cour ...

  4. 中国爬虫违法违规案例汇总github项目介绍

    中国爬虫违法违规案例汇总github项目介绍 GitHub - 本项目用来整理所有中国大陆爬虫开发者涉诉与违规相关的新闻.资料与法律法规.致力于帮助在中国大陆工作的爬虫行业从业者了解我国相关法律,避免 ...

  5. mysql 案例 ~ 常见案例汇总

    一 简介:这里汇总了一些mysql常见的问题二 案例场景   问题1 mysql设置了默认慢日志记录1S,为何会记录不超过1S的sql语句   答案 mysql~log_queries_not_usi ...

  6. mysql 查询优化案例汇总

    一 简介:此文章为经历过的sql案例集合和相关思路 二 案例1: 现象: 测试环境出现select语句,join2张表多次join,explain结果如下 出现 using where,using j ...

  7. Openresty最佳案例 | 汇总

    转载请标明出处: http://blog.csdn.net/forezp/article/details/78616856 本文出自方志朋的博客 目录 Openresty最佳案例 | 第1篇:Ngin ...

  8. angularJS常见问题汇总

    问题描述 解决方案 当你简单的动态给页面插入html时, 此时html带有angular的语法不会执行的. var uploadInfo = '上传成功!<a ng-click="qu ...

  9. AngularJS - 常用方法汇总

    1. 数组元素的常用方法: http://www.cnblogs.com/diaosizhang/p/3729078.html 2. js的强大的splice方法  http://www.jb51.n ...

随机推荐

  1. bidi(双向文字)与RTL布局总结

    BIDI 双向文字就是一个字符串中包含了两种文字,既包含从左到右的文字又包含从右到左的文字. 大多数文字都是从左到右的书写习惯,比如拉丁文字(英文字母)和汉字,少数文字是从右到左的书写方式比如阿拉伯文 ...

  2. 利用avalon 实现一个简单的成绩单

    本文的灵感是来自Halower的这篇博文,他是使用knockout与jQuery实现的.不过我觉得MVVM本来就强大的事件绑定功能,因此用jQuery 是多此一举.另,他也用了一些面向对象的写法.我个 ...

  3. 支持断点续传的文件上传插件——Huploadify-V2.0来了

    之前仿造uploadify写了一个HTML5版的文件上传插件,没看过的朋友可以点此先看一下~得到了不少朋友的好评,我自己也用在了项目中,不论是用户头像上传,还是各种媒体文件的上传,以及各种个性的业务需 ...

  4. 根据Excel的内容和word模板生成对应的word文档

    Sub setname() Dim I As Integer Dim pspname As String Dim pspnumber As String Dim path As String Dim ...

  5. python sorted排序

    python sorted排序 Python不仅提供了list.sort()方法来实现列表的排序,而且提供了内建sorted()函数来实现对复杂列表的排序以及按照字典的key和value进行排序. s ...

  6. Coding Kata - 挑战你的“底线”

    Coding Kata简介 如何进行Kata练习 亲身感受 Coding Kata简介 前段时间听到一个比较有意思的概念叫做Coding Kata,今天试了一下来说说一些想法和思考.Kata是一个日语 ...

  7. Thrift架构~从图中理解thrift,它事实上是一种远程过程调用

    thrift为我们简化了tcp通讯,它可以使用我们方便的建立各种语言的服务端与客户端,并实现客户端对服务器的远程过程调用,简单的说就是服务器通过thrift架构对外开放一些接口,并自己实现这些接口,如 ...

  8. VM~Linux联不上网

    使用桥接的链接方式,centos6.4配置静态ip,能ping通网关,但ping 外网时出现 "network is unreachable" 如:ping www.baidu.c ...

  9. PHP标准库 (SPL) 笔记

    简介 SPL是Standard PHP Library(PHP标准库)的缩写. The Standard PHP Library (SPL) is a collection of interfaces ...

  10. [常见问题]在Linux下执行Redis命令不起作用.

    redis 127.0.0.1:6379> 这个后面无论输入什么命令都没有返回 ok 或者其他的信息,一直保持截图的状态: 解决方法:在SecureCRT中设置Options-->Sess ...