【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

angular随笔

  angular个别情况scope值不能改变或者不能绑定【如:指令内ctrl.$setViewValue()不能直接改变input的val值,该处需要使用scope.$apply】

如之前写的简单指令

var app = angular.module('hpapp', []);
app.directive('inputempty', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            var close = '<span class="clear"></span>';
            elem.next().bind('click', function() {
                ctrl.$setViewValue('');
                ctrl.$render();
            });
        }

    };
});

改变为

var app = angular.module('hpapp', []);
app.directive('inputempty', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            var close = '<span class="clear"></span>';
            elem.next().bind('click', function() {
            ctrl.$apply(function(){
                    ctrl.$setViewValue('');
                });
            });
        }

    };
});            

 

以及下边的情况,在angular内部使用setInterval()以及setTimeout()都不能直接绑定

angular.module('app',[])
    .controller('testController', function($scope) {  
      
      $scope.test = function() {  
        setTimeout(function() { 
            $scope.text = 'test';   
            console.log($scope.text );  
        }, 2000);  
      }  
        
      $scope.test ();  
      
    });  

 

angular.module('app',[])
    .controller('testController', function($scope) {  
      
      $scope.test = function() {  
        setTimeout(function() {  
          $scope.$apply(function() {
            $scope.text = 'test';   
            console.log($scope.text );  
          });  
        }, 2000);  
      }  
        
      $scope.test ();  
      
    });  

 

posted @ 2016-04-20 10:08  happenzh  阅读(140)  评论(0编辑  收藏  举报