当触发事件click()及setTimeout(),$timeout这些要更新DOM要使用apply(),不然模板更新了,但DOM更新不了。 后台可以打印出来, 详细;http://blog.csdn.net/dm_vincent/article/details/38705099
还可以简单粗暴scope。scope.$apply()
<body ng-app="myApp">
<div ng-controller="MessageController">
Delayed Message: {{message}}
</div>
</body>
angular.module('myApp',[]).controller('MessageController', function($scope) {
$scope.getMessage = function() {
setTimeout(function() {
$scope.message = 'Fetched after 3 seconds';
console.log('message:'+$scope.message);
}, 2000);
}
$scope.getMessage();
});
不起作用,以下改善。
angular.module('myApp',[]).controller('MessageController', function($scope) {
$scope.getMessage = function() {
setTimeout(function() {
$scope.$apply(function() {
//wrapped this within $apply
$scope.message = 'Fetched after 3 seconds';
console.log('message:' + $scope.message);
});
}, 2000);
}
$scope.getMessage();
});
事件类型;
<body ng-app="APP">
<script src="https://cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script>
<p>{{message}}</p><input ng-model="message" />
<div><test-dw></test-dw></div>
</body>
var appd = angular.module("APP",[]);
appd.directive("testDw", function(){
return{
//restrict:"A",
//scope:true,
restrict:"AE",
template:"<div><button>点击</button><div>{{message}}</div></div>",
//replace:true,
link:function(scope, element, attrs){
element.bind("click", function(){
//scope.$apply(function(){
scope.message="这就对啦";
console.log(scope.message)
//})
} )
},
}
})
改善,
<body >
<p>{{message}}</p><input ng-model="message" />
<div><test-dw></test-dw></div>
<script src="https://cdn.bootcss.com/angular.js/1.4.0-beta.4/angular-1.4.0-beta.5/angular.js"></script>
<script type="text/javascript">
var appd = angular.module("APP",[])
.directive("testDw", function(){
return{
restrict:"A",
scope:true,
template:"<div><button>点击</button><div>{{message}}</div></div>",
//replace:true,
link:function(scope, element, attrs){
element.bind("click", function(){
scope.$apply(function(){
scope.message="这就对啦";
})
} )
}
}
})
</script>
</body>