I have a {{view Ember.TextField action="foo"}} nested in a <form> tag:
My form:
<form>
{{view Ember.TextField action="foo"}}
</form>
I hoped pressing enter in this textfield will call the action foo, without triggering a submit event on its form (because, by default, Ember.TextField#bubbles is set to false). But it is not the case: the page is reloaded.
For semantic and integration purpose, I would like to keep the <form> tag, and do not write an Ember.Form view.
You can test it in this JSFiddle.
How could I achieve this ?
PS: I'm using ember-latest:
version: v1.0.0-pre.4-31-g16442c5
last commit: 16442c5 (2013-01-23 23:48:09 -0800)
<form {{ action "" on="submit" }}> will prevent the form submission. (This is basically equivalent to the onsubmit="return false;" suggestion in another answer.)
I think the simpliest way is to add onsubmit="return false;" on the form element. Or with jQuery , preventDefault();
I'm sure this is not the best way but it work!
Related
I'm using Ember CLI and have noticed odd behaviour. When the user clicks into the input and presses the enter key, the page refreshes.
My page has a basic element like this that is NOT part of any form:
<input type="text" class="form-control" id="per_page" value="50">
I am currently serving the page via:
ember cli
So node is hosting and has the fancy live reload thing going on so that when I update a page that is part of the underlying app.
So what is causing a page reload the enter key pressed inside an input? Could it be node or live reload? Are inputs just supposed to refresh a page when a user presses the enter key and I missed that in my HTML for dummies book?
**Better still, how can I intercept and instead call a function via:
{{action** "myFunction"}}
That happens because when you hit Enter, form gets submitted which results in page reload. what you need to do is set onsubmit="return false" on the form so nothing happens during submit. you can bind input to execute some action by adding action attribute action="doSomething"
<form onsubmit="return false">
{{input type="text" action="createComment" value=topic id="inputTopic"}}
</form>
Edit: In Ember 3+ you now use the {{on}} modifier to setup events on elements.
<form {{on 'submit' this.submitForm}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
And the action defined like so
#action
submitForm(event) {
event.preventDefault();
// Your code
}
Historically Ember has handled this use case with the following code:
<form {{action 'submitForm' on='submit'}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
This prevents the form from refreshing the page.
There is another method that gives you more control, by giving you the event so you can manage that yourself:
<form onsubmit={{action 'submitForm'}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
In this case, you will get an event and will have to call event.preventDefault() to stop the page refresh.
actions: {
submitForm(event) {
event.preventDefault();
}
}
This is a running example of the two: https://ember-twiddle.com/827820958e054f7af57b7677630729fc?openFiles=controllers.application.js%2C
I had the same problem - what worked for me, was to overwrite the keyPress Event in the input component like this:
keyPress: function (e) {
var keyCodeEnter = 13;
if (e.keyCode === keyCodeEnter) {
return false;
}
}
Hope it will help someone in the future! :)
I have a form in Ember JS and I want to:
1. Display the errors for the fields right next to each field in error ;
2. Display any general errors at the top of the form ;
3. Have these errors persist while the user correct the form.
Edit: JSBin here
I have the following template for the form:
{{#if isSaving}}
<p>Saving Record</p>
{{/if}}
{{#if isError}}
<p>There was an error saving the record</p>
Base errors( {{errors.base}} )
{{/if}}
<form {{action 'create' this on='submit'}}>
<p>Title: {{input type="text" value=title}}</p>
<p>Title Errors( {{errors.title}} )</p>
<p>Body: {{textarea value=body}}</p>
<button>Create</button>
</form>
Right now my server is returning the following
{"errors":{"body":["can't be blank"],"title":["should begin with a capital letter"],"base":["General error message here"]}}
errors.title above is returning an object. How can I get the message out of it.
When the user starts typing, the object message is wiped out.
The isError never seems to fire.
What am I doing wrong?
First: Your errors.title is (like all the other properties of your server response) an Array so you'd get the title with errors.title[0]. As you cannot reference it like this from Handlebars directly you'd either have to provide it from the controller or pass your server response to a custom helper.
Second: It's hard (or better to say impossible) to tell why isError is never triggered/set without code...
errors is an array, and the proper way to iterate over them is the following:
{{#each errors.fieldname}}
{{this.message}}
{{/each}}
I want to use itemcontroller to a render a list of comments as well as perfom CRUD on the comment. The CRUD aspect works fine. But there are two things not working wekll and they are described below. Here is the jsfiddle.
Just click on the add Comment button to see it add an additional edit form underneath the existing one.
When I click on the button to create newComment which uses the CommentNewController, it automatically also renders EmBlog.CommentEditController and comment edit form along side the form for new comment. Both forms are independent of each and use different controllers and templates, so I don't understand why rendering the form for newComment automatically adds an empty form for editComment.
The second issue is that I have an edit button which is surrounded by an #if helper. If the #if helper is true then the edit form should be displayed. To toggle the #if helper to true, I created a button that contains the {{action editComment }}. When I click the button, the edit form is not rendered. But note that, when the template first renders, it automatically displays an edit form, even when the edit button has not been clicked.
Relevant template and controllers ares pasted below.
It is when the post/show template renders that an edit form is automatically displayed without waiting for an edit button to be clicked, which sets the #if helper to true
<script type="text/x-handlebars" data-template-name="posts/show">
//displays the add button link
{{render 'comment.New' }}
<br/>
**render the comments and use CommentEdit as itemController**
{{render 'comments' comments}}
</script>
Comments Template
<script type='text/x-handlebars' data-template-name='comments'>
<ul>
{{#each controller itemController="CommentEdit"}}
<li>{{body}}</li><br/>
{{partial 'comment/edit'}}
{{/each}}
</ul>
</script>
It seems this #if helper is bye-passed as the form is rendered without clicking edit button and when you click edit button, it does nothing
<script type='text/x-handlebars' data-template-name='comment/_edit'>
{{#if controller.editComment}}
{{#if model}}
<form {{action save content on='submit'}}>
{{view Ember.TextArea valueBinding="content.body" placeholder="body"}}
<button type="submit"> save comment </button>
<button {{action cancel content}}> Cancel</button>
</form>
{{/if}}
{{/if}}
<br/>
<div>
<button {{action editComment }} {{bindAttr disabled="isEditingComment"}}> Edit Comment</button>
When you click on the addComment button, it adds a new empty edit form but it shouldn't even be calling the edit form
<script type='text/x-handlebars' data-template-name='comment/new'>
{{#if controller.isAddingNew}}
{{partial 'comment'}}
{{/if}}
<div>
<button {{action addComment}} {{bindAttr disabled="isAddingNew"}}>Add Comment</button>
</div>
</script>
The comment partial for adding new comment
<script type='text/x-handlebars' data-template-name='_comment'>
<form {{action save content on='submit'}}>
<button {{action cancel content}}> Cancel</button>
</form>
</script>
The controllers
EmBlog.CommentNewController = Em.ObjectController.extend({
needs: ['postsShow'],
isAddingNew: false,
addComment: function(){
this.set('isAddingNew', true);
}
});
EmBlog.CommentEditController = Em.ObjectController.extend({
isEditingComment: false,
editComment: function() {
this.set('isEditingComment', true);
}
});
EmBlog.CommentsController = Em.ArrayController.extend({
needs: ['postsShow'],
itemController: 'CommentEdit'
});
Thanks.
working jsfiddle based on mike's answer. Update the ember-data implementation to use Emberjs1.0Rc-6 and the CommentNewController now using Kris Seldon's buffered save as explained here, to avoid error: Attempted to handle event willSetProperty rootState.loaded.updated.inFlight. Thesame code but using ember-model as datastore instead of ember-data: http://jsfiddle.net/TVe4X/4/ and updated to use Emberjs 1.0.0-RC6 and current ember-model : http://jsfiddle.net/tHWM4/5/
When I click on the button to create newComment which uses the CommentNewController, it automatically also renders EmBlog.CommentEditController and comment edit form along side the form for new comment. Both forms are independent of each and use different controllers and templates, so I don't understand why rendering the form for newComment automatically adds an empty form for editComment.
When you click newComment, a new (unsaved) comment is created. Since your comments template uses the each helper to loop over all comments, it is updated to have a new entry. You could get around this by filtering the list based on model state (ie show if isNew), hiding new comments via css or better yet refactor to show the new-comment-form inline. Of course the comment body is blank so you normally would just see a new bullet. But the edit form shows up as well, because of the issue below.
The second issue is that I have an edit button which is surrounded by an #if helper. If the #if helper is true then the edit form should be displayed. To toggle the #if helper to true, I created a button that contains the {{action editComment }}. When I click the button, the edit form is not rendered. But note that, when the template first renders, it automatically displays an edit form, even when the edit button has not been clicked.
Agreed the {{#if editComment}} helper is not working - it always evaluates to true. This is because editComment is a function not a property. Instead you probably want to reference the property isEditingComment.
Updated jsfiddle here: http://jsfiddle.net/mgrassotti/TVe4X/1/
The jsfiddle.
From the posts#index template, I can create a new comment by using the #linkTo helper which goes to the PostNewComment Route and renders the post/newcomment form. If I click save the newly created comment is persisted using the 'save event' inside the PostNewComment Route.
You can uncomment the line below in post/comments" template, to see it working
{{#linkTo "post.newComment"}} Add comment{{/linkTo}}
I changed my UI to use a controller isAddingNew button and the render helper to determine When to display the form and now if I click the save button, I get:
Uncaught TypeError: Cannot call method 'one' of null
This how I render it:
<p> {{render "post.newComment" }} </p>
I suspect it is a scope issue because the error is only triggered when 'save' is clicked after using the render helper.
To reach the 'add new comment' button:
click -> post -> a post title -> click comments link -> add comment
Is there a way to make the 'Post/newComment form' displayed via the 'render helper' in the post/comments template to use the 'save event' defined in the PostNewComment Route.
Right now clicking on the 'save button' which is defined in that form goes directly to the parent route ie PostCommentsRoute instead of going to its own route probably because I displaying the form via the render helper.
I thought calling 'save' should go to its own controller and then bubble to its own route where it is actually defined, before attempting to bubble up the hierarchy to the PostComments Route.
There's probably a few alternatives, but this works and is pretty idiomatic: http://jsfiddle.net/GabSY/4/
In particular:
{{#if model}}
<form {{action save content on='submit'}}>
{{view Ember.TextArea valueBinding="content.body" placeholder="body"}}
<button type="submit"> save comment </button>
<button {{action cancel}}> Cancel</button>
</form>
{{else}}
<button {{action open}}> Add comment </button>
{{/if}}
The reason you were getting the Uncaught TypeError: Cannot call method 'one' of null error was that the PostNewCommentController's model was never set. What I ended up doing was using the open action on the PostNewCommentController to set the model of the controller, which can be used in a Handlebars {{if}} to determine whether the form should be displayed or not.
I prefer this approach to the alternative of setting content/model (they are aliases to each other) of the PostNewCommentController from within the PostCommentsRoute's setupController method because if you go down that route, it's easy to start mixing concerns between not-very-related controllers and routes. In my approach, all the logic for setting the content/model of the new comment takes place in the controller for new comments, which makes sense since a new comment no longer has its own route to initialize this data.
I have a HTML form rendered by Django template tag and I want to manipulate it using AngularJS.
In my template (not rendered) I have:
<html>
<body>
{{ form.as_p }}
</body>
</html>
This is how Django renders this template:
<html>
<body>
<form>
<div id="div_id_street" class="ctrlHolder ">
<label for="id_street">
Street<span>*</span>
</label>
<input id="id_street" type="text" class="textInput textinput" name="street" maxlength="32">
</div>
</form>
</body>
</html>
I want to hide the div div_id_street, but I am not able to add the ng-show or ng-hide directive in my HTML because of the way that Django generates the HTML code.
Is it possible inside an AngularJS controller to show/hide this div?
Thank you!
I was wrong. It is possible to change the template of a Django rendered form.
When defining a django form, I am able to change the widget of each fiels, so I can put the Angular directives in the widget.
For example:
# forms.py
class MyForm(forms.Form):
street = forms.CharField(max_length=80,
widget=forms.TextInput(attrs={
'ng-model': 'street',
'ng-show': 'false',
'ng-change': 'validateStreet()',})
)
This will be rendered as:
<div id="div_street" class="ctrlHolder">
<label for="id_street">Street</label>
<input ng-model="street" name="street" maxlength="80" ng-change="validateStreet()"
ng-show="false" type="text" class="textInput textinput ng-valid ng-dirty"
id="id_street">
</div>
So in my controller I can manipulate this whole field.
Is it possible inside an AngularJS controller to show/hide this div?
Yes, but this "goes deep against the Angular way" -- Misko. Inject $element, then use selectors to find and manipulate. $element is set to the element that your controller is defined on.
function MyCtrl($scope, $element) {
$scope.show = false;
$scope.$watch('show', function (value) {
if (value) {
$element.find('#div_id_street').show();
} else {
$element.find('#div_id_street').hide();
}
})
}
Fiddle -- in this fiddle I used ng-controller.
If you can't modify the template, neither add a class to that specific DIV to add it a ng-show, than you should create a directive to handle this DOM manipulation. You shouldn't do DOM manipulation from within a controller. As stated by the DOCs,
Do not use controllers for:
Any kind of DOM manipulation — Controllers should contain only
business logic. DOM manipulation—the presentation logic of an
application—is well known for being hard to test. Putting any
presentation logic into controllers significantly affects testability
of the business logic. Angular offers databinding for automatic DOM
manipulation. If you have to perform your own manual DOM manipulation,
encapsulate the presentation logic in [directives]http://docs.angularjs.org/guide/directive).
...
I would suggest you to $watch the property you need and manually show/hide the element from inside the link function of a directive.