angularjs使用include后双向绑定失败的解决

原理参考
[url]http://segmentfault.com/q/1010000000738004/a-1020000000738812[/url]
[url]http://blog.csdn.net/dm_vincent/article/details/38705099[/url]
解决参考
[url]http://segmentfault.com/q/1010000002877397[/url]
[url]http://blog.51yip.com/jsjquery/1598.html[/url]
正常是双向绑定如下

<!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;
});
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值