简体   繁体   中英

angularjs: nested ng-repeat creates blank values in selects

Ok, first a simplified portion of the Javascript:

//the network values below are later dynamically 
//reloaded at runtime from a remote API
$scope.networks =  [{id: 5, name: "Network 1"}];

$scope.campaign = {
    paths: [
        {offers: [
             {name: "Site1",
              network: $scope.networks[0],
              uri: "http://uri1.com"},
             {name: "Site2",
              network: $scope.networks[0],
              uri: "http://uri2.com"}]}]};

And the relevant part of the HTML:

<div ng-repeat "path in campaign.paths">
   <div ng-repeat="offer in path.offers">
       <input type="text" ng-model="offer.name" />
       <input type="text" ng-model="offer.uri" />
       <select ng-model="offer.network"
           ng-options="n.id as n.name for n in networks">
       </select>
   </div>
</div>

The problem is that this always gives me a blank option as the first option whenever I try to set the model for the to offer.network . I have read Why does AngularJS include an empty option in select? and AngularJS - extra blank option added using ng-repeat in select tag , but they only seem to apply to selects that are at the top level (ie, not using a model inside an ng-repeat). My problem is that I need to update a model that is part of a nested ng-repeat.

EDIT: I should have also included the below code; this is what is actually breaking everything. This code runs after the original array is set up :

$scope.getNetworks = function () {
    $http.get('/api/networks/nameid'
             ).success(function (data, status, headers, config) {
                 $scope.networks = data;
             });
};
$scope.getNetworks();

The above backend call returns an array of objects of the form {id: id, :name "name"}. And yes, I could populate the select statically from the server side, but I would really like to know how to make this work in the general case.

Since you use the n.id in the comprehension expression of the drop down list, you should pre-populate the offer.network with the id value like this

network: $scope.networks[0].id

And since the data is populated dynamically, you can do something like this. (For the demo purpose, I just use a very dumb way to populate the values. But you get the idea.)

$scope.getNetworks().then(function(data){
    $scope.networks = data;

    //populate the default value
    $scope.campaign.paths[0].offers[0].network = $scope.networks[0].id;
    $scope.campaign.paths[0].offers[1].network = $scope.networks[0].id;
})

Working Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM