我不知道这个问题该怎么写,为了清楚起见,请根据需要进行编辑。
我正在尝试提供一个动画,如果对象的值发生了变化,这对ngClass
来说很容易做到。我根据对象上的值为元素指定一个类。但是,如果确定类的值在加载时已经为true,则动画仍将播放。我该怎么绕过这个?我也不能依赖用户输入来触发更改,因为有异步应用程序事件也可能更改对象值。
示例JSFiddle:https://jsfiddle.net/s6cdgyLb/AngularJS不想玩JSFiddle。。。Plunkr示例:https://plnkr.co/edit/LPJXRq1SWQWrqGaow5tR?p=preview
我正在努力实现这种流程:
Page Load --> Question Answered --> color green
User Answers Question --> Animate --> color green
我得到了这个流程:
Page Load --> Question Answered --> Animate --> color green
User Answers Question --> Animate --> color green
var myApp = angular.module('myApp2', []);
myApp.controller('myController', ['$scope', function($scope){
$scope.list = [
{
value: "Some stuff",
answered: true
},
{
value: "More Stuff",
answered: false
}
];
}]);
myApp.directive('questionCheckbox', function(){
function link(scope, element, attrs){
element.bind('click', function(){
scope.$apply(function(){
question.answered = element.checked;
})
});
};
return {
link: link
}
});
@keyframes answered {
0% {background-color: inherit;}
70% {background-color: hsla(125, 100%, 34%, 0.65);}
100% {background-color: hsla(125, 100%, 34%, 0.2);}
}
.answered {
animation: answered 2s;
animation-fill-mode:forwards;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.10/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="myApp2" ng-controller="myController">
<div ng-repeat="question in list">
<div ng-class="{answered: question.answered}">
<input type="checkbox" ng-model="question.answered">
<span>{{question.value}}</span>
</div>
</div>
</div>
</body>
</html>
您可以使用CSS转换来创建行为。这是因为angular最初会在"answered"类就位的情况下渲染模板,因此它永远不会触发转换。
.answered {
background: hsla(125, 100%, 34%, 0.2);
transition: 2s;
}
希望以下内容可能有用。请注意,如果在完成之前单击另一个复选框,则动画确实会被截断。如果你们想在版本下看到我的更改,我从你们的plunker中分叉出来。
这是我使用的代码。在$scope.list
下面的控制器中,我放入(以下代码)来控制.plain
和.animated
类:
$scope.setIndex = function (index, answered) {
if (answered) {
$scope.selectedIndex = index;
} else {
$scope.selectedIndex = -1;
}
};
我使用了三个不同的类来控制外观:
.answered {
background-color: hsla(125, 100%, 34%, 0.2);
}
.animated {
animation: answered 2s;
animation-fill-mode:forwards;
}
.plain {
background: none;
}
最后,我添加的HTML用于控制.animated
和.plain
类:
<div ng-class="{answered: question.answered, animated: $index === selectedIndex, plain: !question.answered}">
<input type="checkbox" ng-model="question.answered"
ng-click="setIndex($index, question.answered)">
<span>{{question.value}}</span>
</div>