AngularJS(2)——AngularJS数据双向绑定

前端之家收集整理的这篇文章主要介绍了AngularJS(2)——AngularJS数据双向绑定前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

双向绑定


AngularJS在$scope变量中使用脏值检测来实现了数据双向绑定。
Scope作用:
1.通过数据共享连接Controller和View
2.事件的监听和响应
3.脏值检测和数据绑定

双向数据绑定最经常的应用场景就是表单了,这样当用户在前端页面完成输入后,不用任何操作,我们就已经拿到了用户的数据存放到数据模型中了。因为输入框中的ng-model和控制器中的数值实现了双向绑定,所以更改输入框的值或者更改控制器中的值,都会相应的更改双方的值。$scope对象,我们可以理解为NG框架中的一个作用域对象, 在该作用域内可以做到数据和视图的相互绑定,同时又能与其他$scope对象的作用域隔离开来。
当然,$scope也可以实现继承, 在一个controller里面的作用域可以继承它上一级的scope这样就不是独立存在了。


脏值检测


$watch:AngularJS会首先将你在{{ }}中声明的表达式编译成函数调用$watch方法。$watch方法为当前scope注册了一个watcher,这个watcher会被保存到一个scope内部维护的数组中。
$digest : 1.检测(注册的watch函数) 2.通知(就会触发对应的listener函数
$apply:这个方法能够触发$digest方法。$digest方法的执行就标志着一轮Digest Cycle的开始。

一个购物车的例子


  1. <span style="font-family:Microsoft YaHei;font-size:18px;"><!DOCTYPE html>
  2. <html ng-app="mymodule">
  3. <head>
  4. <Meta charset="utf-8">
  5. <link rel="stylesheet" href="css/bootstrap.min.css">
  6.  
  7. </head>
  8. <body>
  9. <div class="panel panel-default panel-primary">
  10. <div class="panel-heading">我的购物车</div>
  11. <div class="panel-body">
  12. <!--ng-repeat ng-click -->
  13. <!--scope注册了一个watcher-->
  14. <!--
  15. 1.AngularJS会首先将你在{{ }}中声明的表达式编译成函数调用$watch方法
  16. -->
  17. <!--
  18. 2.$watch方法的第一个参数是一个函数,它通常被称为watch函数,它的返回值声明需要监听的变量;第二个参数是listener,在变量发生改变的时候会被调用。-->
  19. <table ng-controller="CartController" class="table table-bordered">
  20. <tr>
  21. <th>序号</th>
  22. <th>商品</th>
  23. <th>单价</th>
  24. <th>数量</th>
  25. <th>金额</th>
  26. <th>操作</th>
  27. </tr>
  28. <tr ng-repeat="item in items">
  29. <td>{{$index + 1}}</td>
  30. <td>{{item.name}}</td>
  31. <td>{{item.price | currency}}</td>
  32. <!--filter应用-->
  33. <td><input ng-model="item.quantity"></td>
  34. <td>{{item.quantity * item.price | currency}}</td>
  35. <td>
  36. <button ng-click="remove($index)">Remove</button>
  37. </td>
  38. </tr>
  39. </table>
  40. </div>
  41. </div>
  42. </body>
  43. <script src="js/angular-1.3.0.js"></script>
  44. <script src="ng-repeat.js"></script>
  45. <script src="js/jquery.js"></script>
  46. <script src="js/bootstrap.min.js"></script>
  47.  
  48. </html></span>
  1. <span style="font-family:Microsoft YaHei;font-size:18px;">jS中代码</span>
  1. <span style="font-family:Microsoft YaHei;font-size:18px;">var mymodule=angular.module('mymodule',[]);
  2. mymodule.controller('CartController',['$scope',function CartController($scope) {
  3. $scope.items = [
  4. {name: "Angular应用",quantity: 1,price: 199.00},{name: "Angular入门",price: 139.00},{name: "AngularJS权威教程",quantity: 2,price: 84.20}
  5. ];
  6. //直接绑定事件remove
  7. $scope.remove = function (index) {
  8. $scope.items.splice(index,1);
  9. }
  10. }
  11. ])
  12.  
  13.  
  14. </span>



总结


想象这样的好处,不用页面刷新,数据立刻返回给页面。一直在循环检测是否自己被“污染”了,如果有变化,就通知另一边跟着变化。这样的震荡检测有没有问题呢,双向绑定使用在一个页面上太多,应该也会效率降低吧?请大神们前来交流。

猜你在找的Angularjs相关文章