Let’s consider the following example :
A lot of things are going on in the above example.
In line 16, ng-controller=”FruitsController” defines controller for associated div. It means that the FruitsController function defined in line 5 is the the controller for that particular div. It has a $scope variable which is the viewModel object. We add properties and methods to the $scope object.
We have added two properties “name”(String) and “fruits”(List) and a method addFruit, which adds fruits to the fruits list. Property “name” is initialized to value “Anonymous” and it is associated with the text input in line 17 by using ng-model=”name”. Thus, when the page loads, the text input default value is “Anonymous”.
In line 19, we are fetching items from the fruits list to populate a select box. AngularJS provides ng-options attribute for this purpose. We are also associating the selected item with a variable “selectedFruit” by using the ng-model attribute.
In line 23, we are creating an unordered list from the items of the “fruits” list. AngularJS provides ng-repeat attribute for this purpose.
Line 29 is where the real magic begins. We bind a textbox with variable “newFruit” by using ng-model, such that variable “newFruit” becomes available to the $scope object. Then we created a button and bind its click event by using ng-click attribute such that whenever the button is clicked function addFruit( defined in FruitsController function ) is called $scope.fruits.push($scope.newFruit); appends the fruit name entered by the user (and captured in $scope.newFruit variable) to the list “fruits”.
Now, since the list “fruits” is used by select box as well as unordered list, both of these also get updated dynamically at runtime and you can see the newly added fruit name in both of these.
It is really amazing to see such a bulk of functionality implemented in few lines of code.
You can quickly read the other blogs on AngularJS Series listed below:
- AngularJS : Updating a Label Dynamically with User Input
- AngularJS : Text Suggestions
- AngularJS : Sorting objects on various attributes
- AngularJS : Fetching data from the server
- AngularJS : Multiple Views, Layout Template and Routing
- AngularJS : Implementing Routes And Multiple Views
- Building Intuitive Frontend Interfaces with AngularJS