1

I'm trying to remove an element inside ngRepeat. It's removing well, but after the element is removed, the page is reloaded. How can I prevent this reload action?

Heres the code:

<li ng-repeat="task in tasks">
    <p>{{task.title}}</p>
    <button ng-click="remove($index)">Click me</button>
</li>

js scope:

$scope.remove = function($index){
    $scope.tasks.splice($index, 1);
}
4
  • Why would button click reload the page? Are you sure you have button, not link with some href, and not form that gets submitted? Commented Oct 30, 2014 at 21:02
  • 1
    Sounds like it's the only button inside of a form and it's assuming submit. Confirm it by preventing default action off the event or moving the button outside of your closing form tag. Commented Oct 30, 2014 at 21:03
  • @dfsq yes, its a button. @Antiga I just changed it to an anchor and it worked! Thanks. By the way, its not a form Commented Oct 30, 2014 at 21:07
  • @RamonVasconcelos See my answer for more info and why it's behaving that way. Commented Oct 30, 2014 at 21:08

2 Answers 2

4

As per the W3C spec, the type is undefined and it's assuming a submit. Adding type='button' should resolve the issue for you.

<li ng-repeat="task in tasks">
    <p>{{task.title}}</p>
    <button type="button" ng-click="remove($index)">Click me</button>
</li>

Relevant specification if you're curious.

Sign up to request clarification or add additional context in comments.

2 Comments

You are right. I changed it to input[type=button] but it's still reloading. So I changed it to <a /> and worked.
@RamonVasconcelos Happy to hear you figured it out. Please consider marking answers that solve your problem as the Answer. It's helpful for question visibility.
1

<button> was acting like a submit (thanks to @Antiga), I tried to change it to input[type=button] but still didn't work.

I just made this change:

<button ng-click="remove($index)">Click me</button>

to:

<a ng-click="remove($index)">Click me</a>

And it worked well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.