首页 > 解决方案 > 如何从 ember 中的模板访问 Route 的变量

问题描述

我正在尝试使用 ember 操作在 ember 中进行表单验证。

下面是我的 add.js(route):

    export default Route.extend({
    errorMessage: '',
    model() {
        return this.store.createRecord('contact');
    },
    actions: {
        saveContact(contact) {
            if (contact.get('firstname') === undefined || contact.get('lastName') === undefined || contact.get('mobile') === undefined) {
                this.set('errorMessage', `Some Fields are blank!!`);
            } else {
                this.set('hasBlank', false);
                this.set('errorMessage', "");
                contact.save().then(() => {
                    this.transitionTo("contacts")
                })
            }
        }
    }
});

这是我的模板代码:

<h1>Add Contact</h1>
<div class="full-width">
    <div>{{input class="form-tag half-width" type="text" placeholder="Enter firstName" value=model.firstName}}</div>
    <div>{{input class="form-tag half-width" type="text" placeholder="Enter lastName" value=model.lastName}}</div>
    <div>{{input class="form-tag half-width" type="number" placeholder="Enter mobile Number" value=model.mobile}}</div>
    <button class="form-button half-width" {{action 'saveContact' model}}> Add </button>
{{#if errorMessage}}
     <div class="form-tag half-width">{{errorMessage}}</div>
{{/if}}
</div>

在此模板中,当有空白表单字段时未显示 errorMessage 字段。但如果我将其记录在控制台中,它会显示。

有人可以帮帮我吗?



提前致谢

标签: ember.jsember-cli

解决方案


errorMessage并且您的操作saveContact应该在相应的控制器上而不是路由上。如果您还没有创建相应的控制器,您可以使用ember generate controller <controller-name>. 您的控制器名称应与您的路线名称相对应。

顺便说一句,您将需要使用transitionToRoute而不是transitionTo从控制器操作中进行调用。


推荐阅读