【发布时间】:2014-03-16 07:21:09
【问题描述】:
如何在Angularjs中定义一个获取参数并用ngIf或ngRepeat嵌入子元素的指令?
可以在此处找到该问题的完整演示 - http://jsfiddle.net/2aa47/4/。这是 HTML:
<div ng-controller='myController'>
<my-directive condition="flag">
Both 'flag' and 'a' are defined on controller's scope.
Hi. {{a}} -> Nothing is shown after 'Hi'.
</my-directive>
</div>
还有剧本。在我真正的问题中,我有一个更大的模板,中间有 ngIf。
app.directive('myDirective', function () {
return {
restrict: 'E',
transclude: true,
scope: { condition: '=condition' },
template: '<div ng-if="condition" ng-transclude></div>'
};
});
为了获取参数指令,应该创建一个独立的范围。 ngIf、ngRepeat 和其他类似指令都将创建一个继承自该隔离范围的范围。然后被嵌入的元素将获得后者的作用域兄弟,这意味着直接在指令的孤立元素之下:
Controller's scope
Directive's isolated scope
Scope created by ngIf
Element transcluded by directive. Should be directly under controller's scope
现在指令内的嵌入元素无法访问控制器的范围。如何减轻这种情况?
作为参考,Angular 项目中有这样一个问题 - https://github.com/angular/angular.js/issues/1809。
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope