本篇文章给大家带来的内容是关于angularjs应用:实现类似购物页面的一个小例子(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
写个小应用,熟练一下angularjs.。
<!doctype html><html ng-app='myapp'><head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>page title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="./src/css/index.css" /> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script> var myapp=angular.module('myapp',[]);//定义一个控制器 var model={//model模块,里面主要包含了数据 money:0, items:[ {name:'钢笔',price:50,number:1}, {name:'练习本',price:1,number:0}, {name:'保温杯',price:25,number:0}, {name:'书包',price:80,number:0} ] }; //$scope是angular的一个全局对象,你可以往上面加上属性和方法 myapp.controller('mycontrol',function($scope) {//控制器模块 $scope.model=model;//注意一下,前面的model在html中是看不到的,$scope.model这个model是可以的 $scope是全局对象,注意 $scope.add=function (newitem) {//添加内容 $scope.model.items.push({name:newitem.name,price:newitem.price}); } $scope.sum=function() {//计算费用 var sum=0; angular.foreach($scope.model.items , function (item) { sum+=item.price*item.number; } ); return sum; } $scope.add=function(target) { target.number++; } }) </script> </head><!-- view模块 --><body ng-controller='mycontrol'> <div class='container'> <div class='row'> <div class='col-md-5'> <h2 style='color:red' >总价为: {{sum()}}元</h2> </div> </div> <br> <div class='row'> <div class='col-md-10'> 商品:<input type='text' ng-model='newitem.name'><!-- 值被赋给了newitem.name--> 单价:<input type='text' ng-model='newitem.price'> <button class='btn btn-success btn-md' ng-click='add(newitem)' >添加</button> </div> </div> <br> <div class='row'> <div class='col-md-10'> <table class='table table-striped'> <thead> <tr> <th>商品</th> <th>单价</th> <th>购买数</th> <th>buy or not</th> </tr> </thead> <tbody > <tr ng-repeat='item in model.items' > <td >{{item.name}}</td> <td>{{item.price}}</td> <td>{{item.number}}</td> <td><button class='btn btn-success' ng-click='add(item)'>buy</button></td> </tr> </tbody> </table> </div> </div> </div> </body></html>
运行效果如下:
相关推荐:
angularjs的缓存详解
angularjs实现全选反选功能_angularjs
以上就是angularjs应用:实现类似购物页面的一个小例子(附代码)的详细内容。