javascript - AngularJs ng-if-else 绑定(bind)两个数据模型

标签 javascript jquery html css angularjs

我想知道是否有比我正在做的更好的方法?

我需要根据 $scope.title 值绑定(bind)两个不同的数据模型。因此,在下面的示例中,我为 $scope.title 的每个值创建了两个单独的 DIV。

我可以在里面做吗<div> ?我也没有在这里使用 ng-if-else。我如何在此示例中使用 ng-if-else?

<div>
    <div ng-if="title == 'Add Student'">
    <input type="text" name="name"placeholder="Student Name" data-ng-model="registration.Student.FirstName" maxlength="50">
    </div>

    <div ng-if="title == 'Edit Student'">
    <input type="text" name="name"placeholder="Student Name" data-ng-model="student.Student.FirstName" maxlength="50">
    </div>
</div>

最佳答案

是的,你可以:

<div ng-init="model = (title == 'Add Student' ? registration.Student : student.Student)">
    <input type="text" name="name" placeholder="Student Name" data-ng-model="model.FirstName" maxlength="50">
</div>

为了使它更清晰,您应该将 ng-init 中的部分移动到您的服务或 Controller 中,因为最好将逻辑排除在您的 View 之外。如果您发布检索数据的服务或资源,我可以添加一个示例,说明如何执行此操作。

在我看来,一个更简洁的解决方案是重构您的应用程序,以便学生模型始终具有相同的引用,因此将所有地方的 registration.Student 更改为 student.Student.

关于javascript - AngularJs ng-if-else 绑定(bind)两个数据模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557943/

相关文章:

javascript - 在 JavaScript 中创建时隙时出现问题

javascript - $(input[]).each 仅在 Firefox 中抛出语法错误

javascript - HTML 元素上的静态与动态事件附件

Jquery 事件链接并忽略主题标签

javascript - 如何在 HTML JS 中获取外部文本

Javascript 警报窗口重定向到另一个网页

javascript - Node.js、Express 和 Mongoose,未定义数据

javascript - 你如何在 discord.js 中定义用户的颜色?

javascript - 如何从 ul li 项目中获取文本?

javascript - AngularJS 应用程序模板中的 JS 插件不起作用