Ng-submit and ng-click fires many times i ionic iPhone app

浪尽此生 提交于 2020-01-04 09:09:09

问题


I'm trying out the ionic framework and it looks really nice. However, I have a problem with form submission: the form fires twice. First when the submit button is pressed, and then if I just tap anywhere on the screen. This happens both in the xcode simulator and on my iphone 4gs.

This is what I have done: I install the sidemenu template with: ionic start myApp sidemenu.

I then simply paste this form in to the tab-dash template:

  <form ng-submit="createTask(task)">
        <div class="list">
            <label class="item item-input">
                <input type="text" placeholder="What do you need to do?" ng-model="task.title">
            </label>
        </div>
        <div class="padding">
            <button type="submit" class="button button-block button-positive">Create Task</button>

        </div>
    </form>   

And in my controller I simply have:

 $scope.createTask = function(task) {

        alert(task.title);

    };

This is the only change I made to the starter template, and still the form submits twice. I have no idea why. Would really appreciate some guidance here!


回答1:


Remove the type="submit" from the button and remove the ng-submit from the form and move it as a ng-click on the button itself.

So you should end up with

<button ng-click(createTask) class="...">Create Task</button>



回答2:


This is possibly because whenever the ng-click is called there are two calls made ,one by angular and other by ionic .As ionic and angular comes as a bundle when you are working with ionic project.

You could try one of this method.

1) have ionic and angular javascript seperated in your index.html

instead of including (ionic and angular in one javascript file)

ionic.bundle.min.js

use as

ionic.min.js

angular.min.js

2) Alternatively you can create a directive of your own instead of ng-click like below.

before that Include angular-touch.js and inject ngTouch as a module in your app in app.js

app.directive('myclick', function() {

return function(scope, element, attrs) {

    element.bind('touchstart click', function(event) {

        event.preventDefault();
        event.stopPropagation();

        scope.$apply(attrs['myclick']);
    });
};

});

Hope this helps.




回答3:


in your controller

$scope.createTask = function(task) {
    alert(task.title);
};

add $scope.task= {}; to init



来源:https://stackoverflow.com/questions/25105239/ng-submit-and-ng-click-fires-many-times-i-ionic-iphone-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!