beginnerprogrammer beginnerprogrammer - 1 year ago 38
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.

$scope.insertData=function(){
console.log($scope.comment);
console.log($scope.lang_code);
console.log($scope.user_id);
console.log($scope.product_id);
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) {
console.log(greeting);
if (greeting.data.result == true) {
$scope.requestProductDetail(1,5,1);
$timeout(function () {
window.scrollTo(0,document.body.scrollHeight);
}, 0, false);
}
}, function(reason) {
}, function(update) {
});
}}]);


anyone?

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 (){
                    scope.$eval(attrs.enterKeyPressed);
                });
                event.preventDefault();
            }
        });
    };
});

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