我有这段代码:
HTML code:
<!DOCTYPE html>
<html ng-app="test">
<head lang="en">
<meta charset="utf-8">
<title>Wtf is that</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-controller="testCtrl">
{{test}}
<br />
<button ng-click="set()">set</button>
<button ng-click="setTimeout()">setTimeout</button>
</body>
</html>
AngularJS代码:
var app = angular.module('test', []);
app.controller('testCtrl', function($scope, $timeout) {
$scope.test = false;
$scope.set = function() {
$timeout(function() {
$scope.test = !$scope.test;
}, 1000);
};
$scope.setTimeout = function() {
$('body').slideUp(1000, function () {
$('body').slideDown(1000, function () {
$scope.test = !$scope.test;
console.log($scope.test);
console.log('done');
});
});
};
});
为什么$scope
变量在动画结束后更改时不会发生变化?
超时:
$scope.set = function() {
$timeout(function() {
$scope.test = !$scope.test;
}, 1000);
};
一切正常。
答案 0 :(得分:1)
var app = angular.module('test', []);
app.controller('testCtrl', function($scope, $timeout) {
$scope.test = false;
$scope.set = function() {
$timeout(function() {
$scope.$apply(function() {
console.log("update time clicked");
$scope.test = !$scope.test;
});
}, 1000);
};
$scope.setTimeout = function() {
$('body').slideUp(1000, function() {
$('body').slideDown(1000, function() {
$scope.$apply(function() {
$scope.test = !$scope.test;
});
});
});
};
});
&#13;
<!DOCTYPE html>
<html ng-app="test">
<head lang="en">
<meta charset="utf-8">
<title>Wtf is that</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-controller="testCtrl">
{{test}}
<br />
<button ng-click="set()">set</button>
<button ng-click="setTimeout()">setTimeout</button>
</body>
</html>
&#13;
你需要使用$ scope。$ apply因为 当您在外部(从外部JavaScript)更改AngularJS模型时 - 您需要使用$ scope。$ apply()到AngularJS知道模型已修改。
答案 1 :(得分:0)
因为jQuery动画在Angular范围之外运行。您需要向Angular指定您的范围已更改为:
$scope.$apply();
答案 2 :(得分:0)
如果使用jQuery,Angular不了解DOM操作。要触发摘要周期,您可以使用Unit: milliseconds
expr min lq mean median uq max
sum(m0) 1.016532 1.056030 1.107263 1.084503 1.11173 1.634391
compiler_sum(m0) 7.655251 7.854135 8.000521 8.021107 8.29850 16.760058
neval
100
100
包裹$scope.test = !$scope.test;
以使其正常工作:
$timeout