使用 AngularJS 和 jQuery 修改 DOM (slideDown/slideUp) [英] Modifying DOM (slideDown/slideUp) with AngularJS and jQuery
问题描述
我正在尝试使用 AngularJS 实现一个 slideDown/slideUp 动画.我不能使用 CSS3 的过渡(很遗憾),因为 height
设置为 auto
(我不想使用 max-height
解决方法),所以我正在尝试使用 jQuery 的 slideToggle
方法.
I'm trying to implement a slideDown/slideUp animation with AngularJS. I can't use CSS3's transition (unfortunately) since the height
is set to auto
(and I don't want to use the max-height
workaround), so I'm trying to use jQuery's slideToggle
method.
给定以下标记:
<ul>
<li ng-repeat="entry in data">
<span>{{entry.title}}</span>
<a ng-click="clicked($event)" href>more?</a>
<p>{{entry.description}}</p>
</li>
</ul>
我在控制器中实现了以下方法:
I implemented the following method in my controller:
$scope.clicked = function($event) {
var a = jQuery($event.target);
var p = a.next();
p.slideToggle();
};
即使它似乎按预期工作,我也理解修改 DOM 应仅在指令中完成.
Even if it seems to work as expected, I understood that modifying DOM shall be done exclusively within directives.
在阅读了 AngularJS 的文档(我觉得有点轻率恕我直言)后,指令对我来说仍然有点模糊,所以谁能告诉我以下指令是否尊重 AngularJS 的最佳实践?
After having read AngularJS' documentation (which I find a bit light IMHO), directives are still a bit vague to me, so could anyone tell me whether the following directive respects AngularJS's best pratices or not?
.directive('testDirective', [
function() {
return {
restrict: 'A',
scope: {
entry: '=testDirective'
},
template: '<span>{{entry.title}}</span> ' +
'<a ng-click="clicked($event)" href>more?</a>' +
'<p>{{entry.description}}</p>',
link: function(scope, element) {
var p = jQuery(element.find('p'));
scope.clicked = function($event) {
p.slideToggle();
};
}
};
}])
可以改进吗?我允许在指令中使用 jQuery 吗?它是否尊重关注点分离?
Could it be improved? Am I allowed to use jQuery within a directive? Does it respect the separation of concerns?
推荐答案
或者,你可以使用 AngularJS 的 $animate
:
Alternatively, you can use AngularJS's $animate
:
.animation('.slide', function() {
var NG_HIDE_CLASS = 'ng-hide';
return {
beforeAddClass: function(element, className, done) {
if(className === NG_HIDE_CLASS) {
element.slideUp(done);
}
},
removeClass: function(element, className, done) {
if(className === NG_HIDE_CLASS) {
element.hide().slideDown(done);
}
}
}
});
使用 ng-hide
或 ng-show
来显示或隐藏描述.
Use ng-hide
or ng-show
to show or hide the description.
<li ng-repeat="entry in data">
<span>{{entry.title}}</span>
<a ng-click="expand = !expand" href="#">more?</a>
<p class="slide" ng-show="expand">{{entry.description}}</p>
</li>
参见 JSFiddle
附言你必须包含 jquery
和 angular-animate.js
P.S. you must include jquery
and angular-animate.js
这篇关于使用 AngularJS 和 jQuery 修改 DOM (slideDown/slideUp)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!