AngularJS(2)——AngularJS数据双向绑定
2016-05-08 22:03
841 查看
双向绑定
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的开始。
一个购物车的例子
<span style="font-family:Microsoft YaHei;font-size:18px;"><!DOCTYPE html> <html ng-app="mymodule"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="css/bootstrap.min.css"> </head> <body> <div class="panel panel-default panel-primary"> <div class="panel-heading">我的购物车</div> <div class="panel-body"> <!--ng-repeat ng-click --> <!--scope注册了一个watcher--> <!-- 1.AngularJS会首先将你在{{ }}中声明的表达式编译成函数并调用$watch方法 --> <!-- 2.$watch方法的第一个参数是一个函数,它通常被称为watch函数,它的返回值声明需要监听的变量;第二个参数是listener,在变量发生改变的时候会被调用。--> <table ng-controller="CartController" class="table table-bordered"> <tr> <th>序号</th> <th>商品</th> <th>单价</th> <th>数量</th> <th>金额</th> <th>操作</th> </tr> <tr ng-repeat="item in items"> <td>{{$index + 1}}</td> <td>{{item.name}}</td> <td>{{item.price | currency}}</td> <!--filter应用--> <td><input ng-model="item.quantity"></td> <td>{{item.quantity * item.price | currency}}</td> <td> <button ng-click="remove($index)">Remove</button> </td> </tr> </table> </div> </div> </body> <script src="js/angular-1.3.0.js"></script> <script src="ng-repeat.js"></script> <script src="js/jquery.js"></script> <script src="js/bootstrap.min.js"></script> </html></span>
<span style="font-family:Microsoft YaHei;font-size:18px;">jS中代码:</span>
<span style="font-family:Microsoft YaHei;font-size:18px;">var mymodule=angular.module('mymodule', []); mymodule.controller('CartController', ['$scope', function CartController($scope) { $scope.items = [ {name: "Angular应用", quantity: 1, price: 199.00}, {name: "Angular入门", quantity: 1, price: 139.00}, {name: "AngularJS权威教程", quantity: 2, price: 84.20} ]; //直接绑定事件remove $scope.remove = function (index) { $scope.items.splice(index, 1); } } ]) </span>
总结
想象这样的好处,不用页面刷新,数据立刻返回给页面。一直在循环检测是否自己被“污染”了,如果有变化,就通知另一边跟着变化。这样的震荡检测有没有问题呢,双向绑定使用在一个页面上太多,应该也会效率降低吧?请大神们前来交流。相关文章推荐
- Angularjs【监听数据的变化】和【如何修改数据】和【数据变化的传播】
- AngularJS系列——目录结构
- 30分钟快速掌握AngularJs
- 浅谈angular中的promise
- [置顶] angularJS学习小结——filter
- [后端人员耍前端系列]AngularJs篇:30分钟快速掌握AngularJs
- 学习angularjs遇到的问题
- AngularJS(六)——过滤器
- Angularjs的理解和认识
- angular---常用指令总结
- angularjs中使用ng-repeat渲染最后一个li的时候设置不同样式
- angularJS directive详解
- play+angularjs+karma unit test(单元测试)
- angularjs 创建自定义的指令
- AngularJS自定义指令详解(有分页插件代码)
- 两个很好的angular调试工具-——batarang(stable)和ng-inspector
- AngularJS的启动引导过程
- angularjs中ui-sref传值步骤
- angular
- angular的directive的属性和用法