$apply $digest 都是用來檢測angularjs 的model變化的方法,通常狀況下是不須要使用$apply, 由於angularjs 本身的雙向綁定特性已經能夠將改變的數據自動賦值給頁面傷的變量,但是當有加載延遲的時候須要使用$apply來將數據進行綁定javascript
<!DOCTYPE>
<html ng-app="applyAPP">
<head>
<meta charset="utf-8"/>
<title>star-score</title>
<link rel="stylesheet" type="text/css" href="../public/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../public/bootstrap-theme.min.css">
<script type="text/javascript" src="../public/angular.min.js"></script>
<script type="text/javascript">
var applyAPP = angular.module("applyAPP",[])
. controller("applyController",function($scope){
})
.directive('addTest',function(){
return {
restrict:'AE',
scope: {
text:'='
},
template:'<div ng-if="show">我是測試text文本的{{text}}<button ng-click="add()">點擊我加1</button><button ng-click="backZero()">點擊我歸0</button><button ng-click="ifhide()">點擊我消失</button></div>',
link: function(scope){
scope.text = 0;
scope.show = true;
scope.add = function(){
scope.text ++;
};
scope.backZero = function(){
scope.text = 0
};
scope.ifhide = setTimeout(function(){
scope.show = false; // 注:若是此處不使用setTimeout 函數的話,能夠不使用scope.$apply
scope.$apply();
},10000)css
/*html
scope.ifhide =function(){
scope.show = false; // 注:此處能夠不使用scope.$apply
}java
*/
}
}
})
</script>
</head>
<body ng-controller="applyController">
<add-test text="text"></add-test>
</body>
</html>angularjs