angular js select ng-options

时间:2014-05-23 06:44:20

标签: javascript angularjs

我有一个代码

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 = [];
}]);

和html视图

<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>

如果我按下按钮添加一行就会添加到未使用的OPTION中。在铬它是工作 在Chrome中它工作正常,但在IE9中,如果我添加行并更改她,之前的选项也改变了 这是工作示例http://run.plnkr.co/plunks/43cXzghuFAFkbr2xW75e/#/

1 个答案:

答案 0 :(得分:0)

我不会绑定到数组中的文字。

用对象填充数组,也许只有一个值字段。 {value: 3} 我没有对其进行测试,但这可以解决您的问题。

更好的是,使用每个都有自己范围的指令。在指令返回块中设置scope: true,a.k.a选项。

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

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