anglejs – Angular.js ng切换 – 当不使用动态数据时?
|
我试图让Angular根据我的数据生成一个CSS滑块。我知道数据在那里,并且能够为按钮生成数据,但由于某些原因,代码将不会填充ng开关。当我检查代码,我看到这两次(我知道是正确的,因为我只有两个项目):
<div ng-repeat="assignment in assignments" ng-animate="'animate'" class="ng-scope">
<!-- ngSwitchWhen: {{assignment.id}} -->
</div>
我的实际代码: <div ng-init="thisAssignment='one'">
<div class="btn-group assignments" style="display: block; text-align: center; margin-bottom: 10px">
<span ng-repeat="assignment in assignments">
<button ng-click="thisAssignment = '{{assignment.id}}'" class="btn btn-primary">{{assignment.num}}</button>
</span>
</div>
<div class="well" style="height: 170px;">
<div ng-switch="thisAssignment">
<div class="assignments">
<div ng-repeat="assignment in assignments" ng-animate="'animate'">
<div ng-switch-when='{{assignment.id}}' class="my-switch-animation">
<h2>{{assignment.name}}</h2>
<p>{{assignment.text}}</p>
</div>
</div>
</div>
</div>
</div>
编辑:这是我试图仿效的动态数据。 http://plnkr.co/edit/WUCyCN68tDR1YzNnCWyS?p=preview
从
docs –
所以换句话说,ng-switch是用于模板中的硬编码条件。 你会这样使用它: <div class="assignments">
<div ng-repeat="assignment in assignments" ng-animate="'animate'">
<div ng-switch="assignment.id">
<div ng-switch-when='1' class="my-switch-animation">
<h2>{{assignment.name}}</h2>
<p>{{assignment.text}}</p>
</div>
</div>
</div>
现在这可能并不适合你的用例,所以有可能你需要重新思考你的策略。 Ng-If可能是您需要的 – 同样,您需要注意“isolated” scopes.基本上,当您使用某些指令(如ng-repeat)时,您将创建与父母隔离的新范围。所以如果你改变这个转发中断器,你实际上改变了特定重复块内的变量,而不是整个控制器。 这是一个demo你要做什么。 注意我将选定的属性分配给事物数组(它只是一个对象)。 更新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" class="post post-image">
<img ng-src="{{ post.image }} />
<div ng-bind="post.content"></div>
</div>
<!-- post.type === 'video' -->
<div ng-switch-when="video" class="post post-video">
<video ng-src="{{ post.video }} />
<div ng-bind="post.content"></div>
</div>
<!-- when above doesn't match -->
<div ng-switch-default class="post">
<div ng-bind="post.content"></div>
</div>
</div>
</div>
您可以使用ng-if来实现相同的功能,您的工作是确定应用程序中有意义的内容。在这种情况下,后者更简洁,但也更复杂,如果模板更复杂,您可以看到它变得更加毛茸茸。基本的区别是ng-switch是声明式的,ng-if是必须的。 <div ng-repeat="post in posts">
<div class="post" ng-class="{
'post-image': post.type === 'image','post-video': post.type === 'video'">
<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>
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
