AngularJS指令 - 多重指令元素设置顺序(没有优先的指令,但优先级的元素) [英] AngularJS directive - setting order for multiple directive elements (not priority for directives, but priority for the elements)
问题描述
考虑到与指令富这个标记:
Considering this markup with a directive "foo":
<div foo run="3"></div>
<div foo run="1"></div>
<div foo run="2"></div>
什么是造成富到指定的顺序,而不是从上到下(3,1,2)中运行的好方法?
我能想到这样做会跟踪什么运行,并在不是为了项目返回false,则使得角度再次尝试运行所有这些,重复,直到他们都做的唯一的事情。这听起来很可怕的我虽然,因为这将需要重复这么多次...是否有角内置的东西可以用吗?是否有处理这是一个理想的方法呢?
What is a good approach for causing "foo" to run in the specified order rather than from top to bottom (3,1,2)? The only thing I can think to do would be tracking what has run and returning false on the items that are not in order, then making angular try to run them all again and repeat until they are all done. That sounds terrible to me though, because it would have to repeat so many times... Does Angular have something built-in that can be used? Is there an ideal approach for dealing with this?
推荐答案
OK,这里是我的解决方案,但它更是一个模板。
OK, here's my solution, although it's more a template.
Fiddle (check the console log to see the result)
我已经包裹在一个 fooParent
指令中的富
指令,例如:
I've wrapped the foo
directive in a fooParent
directive, like so:
<div foo-parent>
<div foo run="3"></div>
<div foo run="1"></div>
<div foo run="2"></div>
</div>
的 fooParent
指令存在pretty很多工作要做三件事情:
The fooParent
directive exists pretty much to do three things:
- 暴露
富
项目的功能,使他们能够加入到一个总表 - 维护
FOOS
的名单,该名单将在排序后联 - 过程中的每个
富
在指定的运行秩序。
- Expose a function to
foo
items so they can be added to a general list - Maintain a list of
foos
, which will be sorted during post-linking - Process each
foo
in the run order specified.
它看起来是这样的:
app.directive('fooParent', function() {
var foos = [];
return {
restrict: 'A',
controller: ['$scope', '$element', '$attrs', '$transclude', function($scope, $element, $attrs, $transclude) {
this.addFoo = function(runOrder, element) {
foos.push({
run: 1*runOrder, // make sure run is an integer
element: element
});
};
}],
link: function(scope, element, attrs) {
foos.sort(function(a, b) {
return a.run - b.run;
});
// process all children here
angular.forEach(foos, function(foo) {
console.log(foo);
});
}
};
});
和富
只是看起来像:
app.directive('foo', function() {
return {
restrict: 'A',
require: '^fooParent',
link: function(scope, element, attrs, fooParent) {
fooParent.addFoo(attrs.run, element);
}
};
});
显然,你必须弄清楚处理远程加载内容的最好方式,特别是如果你希望它是连续加载。你的富
指令将变得更加简单,因为加载和处理必须在 fooParent
发生。
Obviously, you will have to figure out the best way to handle remotely loading your content, especially if you want it to be serially loaded. Your foo
directive would become much more simplified, since the loading and processing would have to occur within fooParent
.
这篇关于AngularJS指令 - 多重指令元素设置顺序(没有优先的指令,但优先级的元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!