如何在 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
现在指令内的嵌入元素无法访问 Controller 的范围。如何缓解这种情况?
仅供引用,Angular 项目上存在这样的问题 - https://github.com/angular/angular.js/issues/1809 .
最佳答案
我已经为此找到了一个解决方法 here .
通过将 setTransscope
注入(inject)指令并在链接阶段调用它,正确的范围将被标记为嵌入。应使用 ng-transscope
指令,而不是在模板中使用 ng-transclude
指令,这会恢复之前标记的范围。
指令
myApp.directive('myDirective', function(setTransscope) {
return {
scope: {
display: "="
},
transclude: true, // required
restrict: 'EA',
templateUrl: 'my-template.html',
link: setTransscope
/* ... or call within your own link function:
link: function($scope, $element) {
setTransscope($scope, $element);
// ...
// Other stuff
// ...
} */
};
});
模板
<div ng-if="display">
<div ng-transscope></div>
</div>
关于angularjs - 指令模板中的范围生成不适用于嵌入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434122/