When would you need to dynamically bind ng-model?If your data structure looks like this:
var classes=[
{
"name":"Temperature","options":["cold", "hot", "normal"]},{
"name":"Servings","options":["big", "middle", "small"]}
];
At this point you need to expand the data with ng-repeat,And the options are individually set to the data of ng-options. At this time, it is necessary to dynamically bind the ng-model, so how to bind it?You may need to add a variable under your controller to specify the data for these dynamically rendered ng-options.
So abstract,Let's take a look now.
<!-Dom->
<div class="container">
<div ng-repeat="class in classes">
{{classname}}
<select ng-model="selectdcollection [classname]" ng-options="option for option in classoptions"></select>
</div>
<a ng-click="submit ()">Submit</a>
</div>
//javascript
function democontroller ($scope) {
$scopeclasses=[
{
"name":"Temperature","options":["cold", "hot", "normal"]
},{
"name":"Servings","options":["big", "middle", "small"]
}
];
$scopeselectdcollection=();
$scopesubmit=function () {
console log ($scope selectdcollection);
};
}
In this small piece of program code,We declared $scope.selectdcollection in the democontroller, this is the object that just mentioned to accept the dynamic ng-model value,A button is defined here,After pressing, the value selected by the dynamically rendered ng-options can be thrown to the console of the developer tools.
The actual picture will look like this.
Press Submit to see the following log in the developer tools, and successfully obtain the data.
Related articles
- Inject system functions such as eval, Function in JS to intercept dynamic code
- JS click to dynamically add tags, delete code for specified tags
- vuejs implementation code for dynamically adding class and deleting class at the same level after clicking
- Sample code for dynamically loading and removing js/css files
- JS dynamically modify the background color of the webpage body example code
- JS dynamically added div click to jump to another page to implement code
- Vuejs implements dynamic binding effect of buttons and implements code
- How to intercept dynamic code based on JS