SoFunction
Updated on 2025-04-04

Problems encountered by angularjs using ng-model in ng-repeat

There are many problems when using ng-model in ng-repeat. Some people encounter the inability to obtain bound data content, while others encounter changes to the bound data content and all the content generated by the loop is changed together. I have encountered the above problem during development, but after solving it, I can't restore that situation. I can only briefly introduce how to solve the unavailable scenario.

For example:

html:

<body>
<div ng-controller="selectController">
  <div ng-repeat="pop in citylist">
    <select ng-model="p">
      <option value="" style="display:none;">{{}}</option>
      <option value="Beijing">Beijing</option>
      <option value="Shanghai">Shanghai</option>
      <option value="Guangzhou">Guangzhou</option>
    </select>
    <button ng-click="cs()">ceshi</button>
  </div>
</div>
</body>

js:

<script>
  var app = ('app', []);
  ('selectController', function ($scope) {
    $=[{id:1,pop:"Beijing"},{id:1,pop:"Shanghai"},{id:1,pop:"Guangzhou"}];
    $=function(){
      ($);
    }
  })
</script>

A very simple function. You want to get the currently selected data content when clicking the change button, but you will find that writing in this way can only get undefined. At this time, some people will suggest that p can be assigned to an object and save each selection through the key: value.

$={};

This is indeed OK, but there will be a new problem, that is, as long as one is changed, all the content will be changed together. So is there a better way?

Just a small change

html:

<button ng-click="cs(p)">ceshi</button>

js:

 $=function(p){
      (p);
    }

This is just a simple example. If you find any other problems when using them, you can leave a message in the comments.