【发布时间】:2017-06-03 14:32:21
【问题描述】:
在组件之间切换
我们有两个组件,<hello></hello> 和 <goodbye></goodbye>。这两个组件都具有嵌入性,允许它们以<hello>World</hello> 或<goodbye>World</goodbye> 等方式使用。
angular
.module('myApp', [])
.component('hello', {
template: '<h1>Hello, <ng-transclude></ng-transclude>!</h1>',
transclude: true
})
.component('goodbye', {
template: '<h1>Goodbye, <ng-transclude></ng-transclude>!</h1>',
transclude: true
});
现在,我们希望能够在使用<hello></hello> 组件或<goodbye></goodbye> 之间切换。可以做到这一点的一种方法是使用ng-if。 (Fiddle)
script.js
...
.controller('MyController', ['$scope', function($scope) {
$scope.component = 'hello';
}]);
index.html
<div ng-controller="MyController">
<hello ng-if="component === 'hello'">World</hello>
<goodbye ng-if="component === 'goodbye'">World</goodbye>
</div>
重复代码问题
但是,如果我们的嵌入包含明显更多的行怎么办?我们可能有<hello><!-- Many lines which we'd rather not repeat twice --></hello>,而不是简单的<hello>World</hello>。如果我们用同样的方法来做这件事,我们最终会得到很多重复的代码。所以如果我们可以简单地“切换”组件就好了。 (Fiddle)
<div ng-controller="MyController">
<hello ng-if="component === 'hello'">
<goodbye ng-if="component === 'goodbye'">
Lorem Ipsum.........
</goodbye>
</hello>
</div>
很遗憾,这并没有按预期工作。设置$scope.component = 'hello' 将产生Hello, !,设置$scope.component = 'goodbye' 将产生一个空白页。我对这种行为的解释是,angularjs 将其解析为嵌套在<hello></hello> 中的<goodbye></goodbye>,而不是在使用<hello></hello> 或<goodbye></goodbye> 之间切换。所需的行为更像是 if-else if 语句。
我也尝试过使用ng-switch on。 (Fiddle)
<div ng-controller="MyController">
<div ng-switch on="component">
<hello ng-switch-when="hello">
<goodbye ng-switch-when="goodbye">
Lorem Ipsum.........
</goodbye>
</hello>
</div>
</div>
但是,这会产生多指令资源争用错误。
错误:$compile:multidir
多指令资源争用
Multiple directives [ngSwitchWhen, hello] asking for transclusion on: <hello ng-switch-when="hello">
类似问题
从Using ng-transclude inside ng-switch 的问题中,Github Issue 声称已经修复了一个类似的错误。但是,该修复仅适用于 ng-transclude 嵌套在 <div></div> 块中的情况,如下所示:
<div ng-controller="MyController">
<div ng-switch on="component">
<div ng-switch-when="hello">
<hello>Lorem Ipsum.........</hello>
</div>
<div ng-switch-when="goodbye">
<goodbye>Lorem Ipsum.........</goodbye>
</div>
</div>
</div>
很遗憾,这并不能解决我之前描述的重复代码问题。
所以我的问题是
有没有办法在切换组件的同时保持转置代码不变,而不必多次重写转置代码?
如果没有,我可以使用哪些替代方法来实现我的目标,同时将重复代码的数量保持在最低限度?
【问题讨论】:
标签: angularjs angularjs-ng-transclude angularjs-components