$apply的使用与否

$apply $digest 都是用来检测angularjs 的model变化的方法,一般情况下是不需要使用$apply, 因为angularjs 自己的双向绑定特性已经可以将改变的数据自动赋值给页面伤的变量,可是当有加载延迟的时候需要使用$apply来将数据进行绑定

 

<!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)

 

    /*

   scope.ifhide =function(){
           scope.show = false;  // 注:此处可以不使用scope.$apply
     }

   */
}
}
})
</script>
</head>
<body ng-controller="applyController">
<add-test text="text"></add-test>
</body>
</html>

posted @ 2017-06-20 17:57  木木_Cindy  阅读(209)  评论(0编辑  收藏  举报