AngularJS学习二

来源:互联网 发布:华视微讯网络摄像机 编辑:程序博客网 时间:2024/05/17 04:46
<!DOCTYPE html><html ng-app="myApp"><!--告诉Angular需要它管理哪块内容--><head>    <meta charset="UTF-8">    <title>Title</title>    <!--设置屏幕自适应-->    <meta name="viewport"          content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">    <!--引入angular.js文件-->    <script src="angular.js"></script></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:{{totalCart()|currency}}</div>    <div>Discount:{{bill.discount|currency}}</div>    <div>Subtotal:{{subtotal()|currency}}</div></div><script type="text/javascript">    var app = angular.module('myApp', []);    <!--声明一个模块-->    <!--创建一个控制器,用于数据的业务处理-->    app.controller('CartController', function ($scope) {        $scope.bill = {discount: 0};        $scope.items = [            {title: 'Paint pots', quantity: 8, price: 3.95},            {title: 'Polka pots', quantity: 17, price: 12.95},            {title: 'Pebbles', 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;        }        <!--监听某个变量或者方法,如果值发生了变化就执行后面的指定方法-->        $scope.$watch($scope.totalCart, calculateDiscount);    });</script></body></html>


  • 模型、控制器和模板的关系:
    模型就等于实例对象,整个应用都是由模型驱动的,视图中展示的内容是模型,被存储起来的内容是模型,几乎所有一切都是模型。通过数据绑定技术,视图会根据数据模型自动进行刷新。

    控制器是用来处理业务逻辑的,比如:如何获取模型;可以在模型上执行何种操作;视图需要模型上的何种信息以及如何转换模型以获取想要的信息等。

    模板是用来展示模型的以及用户应该如何与应用进行交互。Angular中的模板不是MVC设计模式中的必备组件。视图是模板编译并执行之后的版本,是模板和数据模型融合之后的产物。模板中不应包含任何形式的业务逻辑或者行为,只有控制器才可以具备这些特性。

0 0
原创粉丝点击