angularjs - 使用指令在预览模板和编辑模板之间切换

标签 angularjs angularjs-directive

我使用 ng-repeat 打印提要中的帖子:

<div ng-ctrl="feedCtrl">
    <feedpost ng-repeat="post in posts"></feedpost>
</div>

这是 feedpost 指令:

.directive('feedpost', function () {
    return {
        restrict: 'E',
        templateUrl: '/views/feed/post.html'
    }
}

这是 Feed 帖子模板的简化版本:

<div class="feedPost">
    <p>{{ post.content }}</p>
    <div>
        <div class="file" ng-repeat="file in post.files">{{ file.name }}</div>
    </div>
    <a ng-click="editPost()">Edit</a>
</div>

我想要实现的目标是用包含表单的 editPost.html 模板替换 post.html 模板,以便在单击编辑链接时编辑帖子(反之亦然,当提交编辑时)。

我已经在谷歌上搜索了一段时间,试图找到解决方案。我所能找到的只是人们使用隐藏表单和 ng-show/hide,但如果有更好的方法的话,我不愿意让 feed 充满隐藏表单。

我考虑过更改 <feedpost>元素到 <editfeedpost>单击编辑链接时,但这似乎不对(而且我不确定如何以 Angular 方式进行操作)。

最佳答案

这里是有根据的猜测,不确定它是否有效。

您可以让您的 feedpost 使用 ng-switch 语句,然后在每个帖子上设置范围级别变量以确定要包含哪个模板。我使用 ng-switch 因为它只包含满足切换条件的 html。

这将是您的指令模板:

<ng-switch on="post.viewMode">
    <ng-switch when="post" ng-include="'/views/feed/post.html'">
    <ng-switch when="edit" ng-include="'/views/feed/edit.html'">
</ng-switch>

这将是 post.html。请注意,我使用 $parent 来解释 ng-include 创建新范围。

<div class="feedPost">
    <p>{{ post.content }}</p>
    <div>
        <div class="file" ng-repeat="file in post.files">{{ file.name }}</div>
    </div>
    <a ng-click="post.$parent.viewMode = 'edit'">Edit</a>
</div>

关于angularjs - 使用指令在预览模板和编辑模板之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17370803/

相关文章:

angularjs - columnFilter 插件不适用于 Angular DataTables 服务器端处理

javascript - Angular .js : reference the current model by short variable name

javascript - AngularJS $http get 不起作用,但 $.ajax 起作用

javascript - 在 ng-messages 中动态设置表单名称

javascript - AngularJS : Access radio button value change in controller

angularjs - Angular 指令 : using ng-model within isolate scope

javascript - Angular : Variable template inside directive

javascript - 来自http响应的 Angular 局部变量绑定(bind)

javascript - 针对常量求值的 Angular 表达式

javascript - AngularJS 无法让我的匹配(两个字段)指令工作