Learn working with Arrays in AngularJS



In this tutorial, we’re going to work with an array and see what features of AngularJS we can utilize to manage it. We’re going to use features of Angular forms as well as arrays to make our array dynamic and user-interactive.

We’re going to start our demonstration by using the grocery list array we have created in a previous tutorial:

We want to allow the user to be able to add items to the array/grocery list by clicking a button. For that we’ll have to create a new $scope property, like so:

Explanation: addItem is a parameter that holds the value the user enters in the text input box. When a button is clicked, the value of the addItem is added to the array using the above function. The function first checks if the user entered a defined string, in which case it uses the push method to add the item into the array(as an object, with a default of needed:false). Otherwise, it sets the NoItemError attribute to include an error message.

We are going to connect the ‘backstage’ data with the view(HTML), referencing the controller we have created and binding the data the user enters to the addItem parameter using ng-model:

When the user clicks the button, it triggers the addTolist function. If the user didn’t type anything in the input field, the  value of NoItemError will be set to an error message that will then be displayed in the expression, inside <h2> tags.

All that’s left to do now is to display the grocery list using the ng-repeat directive with the lst property and referencing our controller:

So, this is how we can add items to arrays using AngularJS. Let‘s write the code in full and see it in action:


To summarise, in this lesson we’ve used an array of objects to demonstrate how we can utilise AngularJS to easily create a dynamic and user-interactive list. As we’ve demonstrated, we can easily bind data using Angular directives and pass it into $scope functions as a parameter or trigger &scope functions as properties to DOM events.



Please enter your comment!
Please enter your name here