angular随笔

时间:2022-09-19 07:21:47

  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 (); });