In this post we will be exploring dynamic models inside ng-repeat of AngularJS.
We will be creating dynamic models and will try to access them in our controller.
Need : While generating a repetitive HTML markup through ng-repeat ,other then just normal displaying of data sometimes we also need to generate some controls like textboxes , chackboxes etc. We need to have a model which we can bind with these controls for retrieving their value as and when needed in controller.
There are many ways to achieve , we will be doing it through creating a new property in the looping object. So let’s begin.
Scenario : We have a list of developers with every developer having properties like Name, Project Count. We will be generating dynamic textboxes and will bind models to them and will finally try to access their values in the controller.
Generating Dynamic Models:
In the above code you can see other then two properties(Name and ProjectCount) , We are also generating textboxes against every developer.
For these dynamic textboxes when you will look into the ng-model then you will see that it is”developer.mydata” . So basically here we have created one more property(mydata) dynamically in the developer object which will work as model for the corresponding textbox.
Suppose if there are 5 developers means 5 textboxes , every textbox is bound to a unique model which is “mydata” property of that particular developer object to which the textbox belongs.
Accessing the dynamic models:
The dynamic model is now a part of the developer object. So whenever you need to access any particular model you just need to accesss the $scope.developers in the controller and based on some conditions you can easily retrieve the model(i.e textbox value).
If you have a specific set of functionality like there is a button next to every textbox for saving it’s value to the Database or anything you just need to call the ng-click of the button with current developer object in the param and then you can access the “mydata” property which is the textbox value.
Like in above example what i have done is that i need the textbox value as an when the end user move out of the textbox. So for achieving this, using ng-blur I have called a method SaveValue and I am passing the developer object inside it.
Inside SaveValue method we are retrieving the textbox value from it’s model which is present in the passed developer object and then we can use it for any type of user action.
This is not the only way of handling the dynamic models but is surely a very effective one.