核心提示:AngularJS在$scope变量中使用脏值检测来实现了数据双向绑定。Scope作用:1.通过数据共享连接Controller和View2.事件的监听和响应3.脏值检测和数据绑定双向数据绑定最经常的...
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的开始。
一个购物车的例子
<meta charset="utf-8" /> <link href="css/bootstrap.min.css" rel="stylesheet" /> <span style="font-family:Microsoft YaHei;font-size:18px;">我的购物车</span> <table class="table table-bordered" ng-controller="CartController"> <tbody> <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> </tbody> </table> <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>
jS中代码:
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); } } ])
总结
想象这样的好处,不用页面刷新,数据立刻返回给页面。一直在循环检测是否自己被“污染”了,如果有变化,就通知另一边跟着变化。这样的震荡检测有没有问题呢,双向绑定使用在一个页面上太多,应该也会效率降低吧?请大神们前来交流。