我正在尝试将$animate服务合并到我自己的指令中。我不能进入和离开真正的动画。
奇怪的是,使用$animate.enter时,元素被附加到DOM中,并触发回调函数。但似乎从未添加过ng-animate、ng-enter和ng-enter-active类。元素只是简单地附加到DOM中,没有动画。回调函数会触发,但它会立即触发,而不是在本应发生的动画持续时间之后。同样的事情也发生在leave上;元素会立即从DOM中移除,回调也会立即触发;没有动画效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>$animate.enter</title>
<script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.14/angular.js" data-semver="1.2.14"></script>
<script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.5/angular-animate.js" data-semver="1.2.5"></script>
<script type="text/javascript" charset="utf-8">
var app = angular.module('TestAnimation', []);
app.controller('TestAnimation', function($scope) {
});
app.directive("appendaroo", function($animate, $compile) {
function link(scope, element, attr) {
var isAppended = false;
var parent = element.parent();
var box;
element.on('click', function() {
isAppended = !isAppended;
if (isAppended) {
box = angular.element('<div class="rect"></div>');
$animate.enter(box, parent, element, function() {
console.log("Done entering");
});
} else {
$animate.leave(box, function() {
console.log("Done leaving");
});
}
});
}
return {
link: link
};
});
</script>
<style type="text/css" media="screen">
.rect {
width: 100px;
height: 100px;
background-color: #ff9933;
transition: all 1s ease-out;
}
.rect.ng-enter,
.rect.ng-leave.ng-leave-active {
opacity: 0;
}
.rect.ng-enter.ng-enter-active,
.rect.ng-leave {
opacity: 1;
}
</style>
</head>
<body ng-controller="TestAnimation" ng-app="TestAnimation">
<button appendaroo>Fade in/out</button>
</body>
</html>我是Angular的新手,我想我只是错过了一些东西,所以如果这是一个疯狂的愚蠢的问题,很抱歉。但是在您自己的指令中似乎没有太多可用的资源来利用$animate。
我可以毫无问题地使用$animate.addClass和$animate.removeClass,这很有帮助,并表明我在正确的轨道上,但enter和leave给我带来了问题。
我把这个例子放在Punker上:
http://plnkr.co/edit/XtvZAZzgA8ORZBaRN68d?p=preview
发布于 2014-03-18 01:56:12
要使用ngAnimate模块,您需要将其作为依赖项添加到您的模块:
var app = angular.module('plunker', ['ngAnimate']);您没有得到任何异常的原因是基本模块包含一个$animate服务,该服务具有documentation中描述的默认实现(有点令人困惑的是):
done的默认$animate实现,它不执行任何动画,而只是同步执行DOM更新和调用
()回调。
为了启用动画,必须加载ngAnimate模块。
要查看函数实现,请查看src/ngAnimate/animate.js
将ngAnimate模块添加为依赖项后,您的代码仍然不会像您希望的那样运行。然而,这是因为一些完全不同的东西,与$animate服务没有真正的关系:
.on()是一个包含在Angular的jqLite中的jQuery方法。附加事件处理程序中的代码位于Angular之外,因此您需要使用$apply:
$apply()用于从angular框架外部执行angular中的表达式。(例如,来自浏览器DOM事件、setTimeout、XHR或第三方库)。因为我们正在调用angular框架,所以我们需要执行异常处理的适当作用域生命周期,执行监视。
像这样包装你的$animate调用,你的代码就会工作得很好:
scope.$apply(function () {
$animate.enter(box, parent, element, function() {
console.log("Done entering");
});
});
scope.$apply(function () {
$animate.leave(box, function() {
console.log("Done leaving");
});
});演示: http://plnkr.co/edit/iWHBNyKfwiSUUFKrMQff?p=preview
https://stackoverflow.com/questions/22461136
复制相似问题