我有一个指令,可以嵌入原始内容,对其进行解析,并使用原始内容中的信息来帮助构建新内容。它的要点如下:
.directive('list', function() {
return {
restrict: 'E',
transclude: true,
templateUrl: '...',
scope: true,
controller: function($scope, $element, $attrs, $transclude) {
var items;
$transclude(function(clone) {
clone = Array.prototype.slice.call(clone);
items = clone
.filter(function(node) {
return node.nodeType === 1;
})
.map(function(node) {
return {
value: node.getAttribute('value')
text: node.innerHTML
};
});
});
// Do some stuff down here with the item information
}
}
});
然后,我这样使用它:
<list>
<item value="foo">bar</item>
<item value="baz">qux</item>
</list>
这一切都像这样工作得很好。当我尝试使用时出现问题ng-repeat
在指令内容中,如下所示:
<list>
<item ng-repeat="item in items" value="{{ item.value }}">{{ item.text }}</item>
</list>
当我尝试这样做时,没有任何项目。任何人都知道为什么这行不通,或者是否有更好的方法来完成同样的事情?
您可以尝试:
transcludeFn(scope, function (clone) {
iElem.append(clone);
})
有关更多详细信息:
HTML:
<foo data-lists='[lists data here]'>
<li ng-repeat="list in lists">{{list.name}}</li>
</foo>
指示:
var Foo = function() {
return {
restrict: 'E',
template: '...'
transclude: true,
scope: { lists: '=?' }
link: function(scope, iElem, iAttrs, Ctrl, transcludeFn) {
transcludeFn(scope, function (clone) {
iElem.append(clone);
}
}
};
};
.directive('foo', Foo);
您应该让 transcludFn 知道您将在 transcludeFn 中使用哪个作用域。如果您不想使用隔离范围,您也可以尝试transcludeFn(scope.$parent....)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)