如何将一些 jQuery 函数转换为 angularjs 指令?
Posted
技术标签:
【中文标题】如何将一些 jQuery 函数转换为 angularjs 指令?【英文标题】:how to convert some jQuery functions into angularjs directive? 【发布时间】:2017-02-27 15:52:30 【问题描述】:我会写 jQuery。但是,我对angularjs知之甚少。我制作了一个 jQuery 场景,我必须在 angularjs 项目中使用它。请have a look in my jQuery sample。我正在尝试将此jQuery scenario
转换为angular directive
。前面说了,我不是很了解angularjs,所以无法成功。但是,我试图使它成为with angular directive at this fiddle。但是,有很多错误/错误-我相信并且我不清楚如何成功完成它。你能帮我把这个 jQuery 转换成 anguarjs 指令吗?提前致谢
【问题讨论】:
【参考方案1】:你可以将你的函数从链接函数中分离出来,以便在窗口调整大小和加载时通过传递由jQuery包裹的角度元素来重用它。
还有:
在您原来的小提琴中,缺少 angularjs 初始化ng-app="App"
。这导致您的应用程序永远无法运行。
在声明指令时,它使用camelCase 语法caclulateRow
。但是在 html 上应用它时,您必须使用类似 XML 的语法 (dash-delimited);即caclulate-row
。
var app = angular.module('App', []);
app.directive("caclulateRow", [function ()
function tableAdjustedHeight(el)
var firstColHeight = el.find('td:nth-child(1)').outerHeight();
var secondColHeight = el.find('td:nth-child(2)').outerHeight();
var thirdColHeight = el.find('td:nth-child(3)').outerHeight();
var fourthColHeight = el.find('td:nth-child(4)').outerHeight();
el.find('td:nth-child(2)').css('top', firstColHeight);
el.find('td:nth-child(4)').css('top', thirdColHeight);
var leftColHeight = firstColHeight + secondColHeight;
var rightColHeight = thirdColHeight + fourthColHeight;
var colHeightArray = [leftColHeight, rightColHeight];
var largeHeight = Math.max.apply(null, colHeightArray);
el.height(largeHeight);
return
restrict: "A",
scope:
,
link: function (scope, element, attr)
var el = $(element);
if ($(window).width() < 992)
tableAdjustedHeight(el);
$(window).resize(function ()
tableAdjustedHeight(el);
);
;
]);
.table td
width: 25%;
@media (max-width: 991px)
.table tr
position: relative;
.table td
display: inline-block;
width: 50%;
.table td:nth-child(2)
position: absolute;
left: 0;
.table td:nth-child(4)
position: absolute;
right: 0;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<table class="table" ng-app="App">
<tr class="main-row" caclulate-row>
<td>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text</td>
<td>Text Text Text Text</td>
<td>Text Text Text Text Text Text</td>
<td>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text</td>
</tr>
</table>
【讨论】:
以上是关于如何将一些 jQuery 函数转换为 angularjs 指令?的主要内容,如果未能解决你的问题,请参考以下文章