60
 $scope.itemarray = ['A', 'B', 'C'];  

this will clear the array but the ui wont be updated.

$scope.itemarray = [];

this works fine! why?

 $scope.itemarray.length = 0;  
3
  • 1
    Can you provide a jsfiddle or example Commented Apr 22, 2015 at 16:06
  • Do you have some sort of ng-submit happening before your clear event perhaps? Maybe you're adding to the array somehow then trying to clear it. Otherwise = [] should be working fine Commented Apr 22, 2015 at 16:10
  • You may be doing something like the following: jsfiddle.net/9mth0knf (goes along with Petr Averyanov's answer) Commented Apr 22, 2015 at 16:33

1 Answer 1

89

$scope.itemarray.length = 0; << this is correct. Length is read-write property.

$scope.itemarray = []; << this creates new empty array. If you have bindings to old itemarray, they may be lost. (Html binding like ng-if="itemarray[0]" wont be lost)

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

1 Comment

Being able to set the length on an array is bizarre but it is also the absolute fastest way to clear an array in JavaScript

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.