beginnerprogrammer beginnerprogrammer - 1 year ago 34
AngularJS Question

insert data to database using enter button

i want to add new comment to my database by using input text, but i don't want to use form or onclick. here's is my input text structure

<input type="text" class="comment_input" ng-model="comment" ng-model-options="{updateOn : 'change blur'}" placeholder="To enter" />

When i try to using bind, it show my comment when i push enter button, but i want to insert it to my database API.. Here's is my function for inserting the data.

var dataPromise = Data.setData("API_URL","user_id="+$scope.user_id+"&product_id="+$scope.product_id+"&comment="+$scope.comment+"&lang="+$scope.lang_code);
dataPromise.then(function(greeting) {
if ( == true) {
$timeout(function () {
}, 0, false);
}, function(reason) {
}, function(update) {


ah, and how to refresh this page after i doing something? *insertdata / onclick button

Answer Source

You can use this directive to trigger enter key event

app.directive('enterKeyPressed', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){

Use it from html as below

<input type="text" class="comment_input" ng-model="comment" enter-key-pressed="insertData()" placeholder="To enter" />

If you are using ng-repeat to display comments, just push the new comment into comments array

To reload the page, you can use the reload method of the $route service. Inject $window in your controller and then call $window.location.reload() at the end of insertData() function

Hope it helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download