如何从ember中的模板访问Route的变量

时间:2018-06-04 13:04:41

标签: ember.js ember-cli

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

以下是我的add.js(路线):

    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字段。但是,如果我在控制台中记录它,则会显示它。

有人可以帮助我吗?



在此先感谢

1 个答案:

答案 0 :(得分:3)

errorMessage并且您的操作saveContact应位于相应的控制器而不是路径上。如果您尚未创建相应的控制器,则可以使用ember generate controller <controller-name>执行此操作。您的控制器名称应与您的路线名称相对应。

顺便说一下,当你从控制器动作拨打电话时,你需要使用transitionToRoute而不是transitionTo