简体   繁体   中英

angular js select ng-options

I have a code

app.controller('SelectCtrl', ['$scope', '$routeParams', '$http', '$q', 
    function($scope,    $routeParams, $http, $q) {

    var deferred = $q.defer();
    $http.get('json/newjson.json').success(function(responce) {
        deferred.resolve(responce);
    });

    deferred.promise.then(function(data) {
        $scope.values = data;
        $scope.recepients = [20, 23];
        $scope.ids = _.pluck($scope.values, "id");
        $scope.free = _.difference($scope.ids, $scope.recepients);
        recalc();
    });


    function recalc() {
        $scope.recepients.forEach(function(v, index) {
            $scope.vals[index] = [];
            $scope.ids.forEach(function(val, i) {
                if (_.indexOf($scope.free, val) > -1 || val === $scope.recepients[index]) {
                    $scope.vals[index].push($scope.values[i]);
                }
            });
        });
    }

    $scope.add = function() {
        if ($scope.recepients.length < $scope.values.length) {
            $scope.recepients.push($scope.free.shift());
            recalc();
        }
    };

    $scope.remove = function(index) {
        $scope.recepients.splice(index, 1);
        $scope.free = _.difference($scope.ids, $scope.recepients);
        recalc();
    }

    $scope.change = function() {
        $scope.free = _.difference($scope.ids, $scope.recepients);
        recalc();
    };

    $scope.vals = [];
}]);

and html view

<table class="table">
  <tr data-ng-repeat="recepient in recepients">
    <td class="col-md-8">
        <select class="form-control" data-ng-model="recepients[$index]" data-ng-change="change()" data-ng-options="type.id as  type.name for (key , type) in vals[$index]"></select>
    </td>
    <td>
        <button class="btn btn-danger" data-ng-click="remove($index)"><span class="glyphicon glyphicon-remove"></span>remove</button>
    </td>
  </tr>
</table>
<button data-ng-click="add()" class="btn btn-success"><span class="glyphicon glyphicon-plus"></span>add</button>

If I push the button to add a row is added to the unused OPTION. in chrome it is work in chrome it works fine, but in IE9 if i add row and change her, previous options changed too here is working example http://run.plnkr.co/plunks/43cXzghuFAFkbr2xW75e/#/

I wouldn't bind to a literal in an array.

Fill the array with objects , perhaps just have a value field. {value: 3} I didn't test it, but that should fix your problem.

Even better, use a directive each with their own scope. set scope: true in the directive return block, aka options.

https://docs.angularjs.org/guide/directive

How to prevent that a scope is shared among directives n Angular?

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