秒味课堂Angular js笔记------$scope.$watch和$scope.$apply

  • $scope.$watch(watchFn , watchAction , deepWatch)

        其中,watchFn是带有angular表达式或函数字符串;

                watchAction是一个函数或者表达式,当watchFn发生变化时调用,如果是函数,其签名是function(newValue, oldValue, scope);

                deepWatch如果是ture,则会检查被监控对象的每一个属性是否发生了变化。

<script type="application/javascript">
            var modelMy = angular.module('modelMy',[]);
            modelMy.controller('shopList',['$scope',function($scope){ //scope容易被压缩成简短的其他字符 可以用第二种方法
                $scope.unitPrice = 38;
                $scope.count = 3;
                $scope.fre = 8;
                $scope.total = function(){
                    return $scope.unitPrice * $scope.count;
                };
/*              $scope.$watch( 'count' , function(value){  //监听$watch 单个''
                    console.log(value);
                })*/
                $scope.$watch( $scope.total , function(value){ //监听$watch 函数
                    $scope.fre = value >= 100 ? 0 : 8;
                })
            }])
</script>
  • $scope.$apply
<body ng-app="myApp">  
  <div ng-controller="MessageController">  
    Delayed Message: {{message}}  
  </div>    
</body>
<script>
 var m1 = angular.module('myApp',[]);
  m1.controller('MessageController', function($scope) {        
      $scope.getMessage = function() {  
        setTimeout(function() {  
          $scope.$apply(function() {  // 在这应用$apply方法
            $scope.message = '2秒后显示该文字';   
            console.log('message:' + $scope.message);  
          });  
        }, 2000);  
      }  
        
      $scope.getMessage();  
      
    });  
</script>
原文地址:https://www.cnblogs.com/lovemomo/p/6104466.html