来自文档 -
请注意,要匹配的属性值不能是表达式。它们被解释为要匹配的文字字符串值。例如,ng-switch-when =“ someval”将匹配字符串“
someval”,而不是表达式$ scope.someval的值。
因此,换句话说,ng-switch用于模板中的硬编码条件。
您可以这样使用它:
<div > <div ng-repeat="assignment in assignments" ng-animate="'animate'"> <div ng-switch="assignment.id"> <div ng-switch-when='1' > <h2>{{assignment.name}}</h2> <p>{{assignment.text}}</p> </div> </div></div>现在,这可能并不完全适合您的用例,因此您可能必须重新考虑自己的策略。
Ng-If可能正是您所需要的-
另外,您需要了解“隔离的”范围。基本上,当您使用某些指令(例如ng-
repeat)时,会创建与其父级隔离的新作用域。因此,如果
thisAssignment在转发器内部进行更改,则实际上是在更改该特定重复块内部的变量,而不是整个控制器。
这是您要做什么的演示。
注意,我将选定的属性分配给
things数组(它只是一个对象)。
更新12/12/14:添加新的代码块以阐明的使用
ng-switch。上面的代码示例应被视为 不要 执行的操作。
正如我在评论中提到的。应当像考虑Javascript开关一样考虑开关。用于硬编码的交换逻辑。因此,例如在我的示例帖子中,只会有几种类型的帖子。您应该很早就知道要打开的值的类型。
<div ng-repeat="post in posts"> <div ng-switch on="post.type"> <!-- post.type === 'image' --> <div ng-switch-when="image" > <img ng-src="{{ post.image }} /> <div ng-bind="post.content"></div> </div> <!-- post.type === 'video' --> <div ng-switch-when="video" > <video ng-src="{{ post.video }} /> <div ng-bind="post.content"></div> </div> <!-- when above doesn't match --> <div ng-switch-default > <div ng-bind="post.content"></div> </div> </div></div>您可以使用来实现相同的功能
ng-if,这是确定应用程序中什么才有意义的工作。在这种情况下,后者要简洁得多,但也要复杂得多,如果模板更加复杂,您会发现它变得更加毛茸茸。基本的区别是
ng-switch说明性的,
ng-if必须的。
<div ng-repeat="post in posts"> <div ng-> <video ng-if="post.type === 'video'" ng-src="post.video" /> <img ng-if="post.type === 'image'" ng-src="post.image" /> <div ng-bind="post.content" /> </div></div>



