http://segmentfault.com/q/1010000000738004/a-1020000000738812
http://blog.csdn.net/dm_vincent/article/details/38705099
解决参考
http://segmentfault.com/q/1010000002877397
http://blog.51yip.com/jsjquery/1598.html
正常是双向绑定如下
<!DOCTYPE html> <html ng-app="myapp"> <head> <meta charset="utf-8"> <title>ng-model directive</title> </head> <body ng-controller="HelloController"> <script src="angular.min.js"></script> <script> var app=angular.module("myapp",[]); app.controller("HelloController",function($rootScope,$scope) { $scope.greeting="haoning"; $scope.consoleng = function() { console.log($scope.greeting) ; } }); </script> <div> <p>bbbbbbbbb</p> <input id="thism" ng-model="greeting" > <p>Hello {{greeting || "World"}}</p> <button ng-click="consoleng()" >dayin</button> <button ng-click="cha()">cha</button> <hr> </div> </body> </html>
$scope.greeting与ng-model="greeting"
绑定,党model变了,打印的scope的greeting也变了
然而如果引入了ng-include 的子页面
在子页面改了model之后,scope中的数据没有如期改变
需要处罚apply方法使数据改变,apply又存在安全问题,
解决办法如下
外层的为
out.html
<!DOCTYPE html> <html ng-app="myapp"> <head> <meta charset="utf-8"> <title>ng-model directive</title> </head> <body ng-controller="HelloController"> <script src="angular.min.js"></script> <script> var app=angular.module("myapp",[]); app.controller("HelloController",function($rootScope,$scope) { $scope.safeApply = function(fn) { var phase = this.$root.$$phase; if (phase == '$apply' || phase == '$digest') { if (fn && (typeof(fn) === 'function')) { fn(); } } else { this.$apply(fn); } }; $scope.greeting="haoning"; $scope.consoleng = function() { console.log($scope.greeting) ; } $rootScope.cha = function() { console.log("cha"); $scope.safeApply(function () { $scope.greeting = document.getElementById("thism").value; }); } }); </script> <div ng-include="'inner.html'" class="sidebar sidebar-right"></div> </body> </html>
内层的为
inner.html
<div> <p>bbbbbbbbb</p> <input id="thism" ng-model="greeting" > <p>Hello {{greeting || "World"}}</p> <button ng-click="consoleng()" >dayin</button> <button ng-click="cha()">cha</button> <hr> </div>
使model的值改变后,手动触发一下apple那个方法,
才能改变scope中的值
分析,
加了
$scope.safeApply = function(fn) { var phase = this.$root.$$phase; if (phase == '$apply' || phase == '$digest') { if (fn && (typeof(fn) === 'function')) { fn(); } } else { this.$apply(fn); } };
和
$rootScope.cha = function() { console.log("cha"); $scope.safeApply(function () { $scope.greeting = document.getElementById("thism").value; }); }