在slice()

时间:2017-05-13 12:00:15

标签: javascript angularjs angularjs-ng-repeat

我选择使用数组中的ng-repeat:

  <select data-ng-model='selectedTagForNew'   ng-change="selectedTagForNewChange()" >
        <option ng-value="{{tag.arrayindex}}"  data-ng-repeat="tag in tags |orderBy:'seq'">{{tag.seq}}&nbsp;{{tag.name}}&nbsp;({{tag.number}})</option>
    </select>

在我的控制器中执行某些操作时,我从数组中删除了所选元素:

    tags.splice($scope.selectedTagForNew,1);
    for(i=0;i<tags.length;i++){
            tags[i].arrayindex=i;
   }
    $scope.tags=tags;

问题在于,每次在选定数组中的最后一个元素slice()之后,选择$scope.selectedTagForNewundefinedtags[$scope.selectedTagForNew]。结果nulltag.arrayindex对象即使它显示在列表中。 我做错了什么?

更新:经过多次测试后,似乎ng-repeat没有更新,所以给出了模型的旧值(Game(); function Game() { this.rows = 6; // Height this.columns = 7; // Width this.status = 0; // 0: running, 1: won, 2: lost, 3: tie this.depth = 4; // Search depth this.score = 100000, // Win/loss score this.round = 0; // 0: Human, 1: Computer this.winning_array = []; // Winning (chips) array this.iterations = 0; // Iteration count var that = this; that.init(); } Game.prototype.init = function() { // Generate 'real' board // Create 2-dimensional array var game_board = new Array(that.rows); for (var i = 0; i < game_board.length; i++) { game_board[i] = new Array(that.columns); for (var j = 0; j < game_board[i].length; j++) { game_board[i][j] = null; } }

2 个答案:

答案 0 :(得分:0)

更好的切片方式

在打字稿中

const pos = this.tags.map(elem => { return tag._id; }).indexOf(tag._id);
this.tags.splice(pos, 1);

在JavaScript中,您可以进行扩展

Array.prototype.spliceObject = function (sourceToRemove) {
        //Remove the deleted entry from list
        var index = this.indexOf(sourceToRemove);
        if (index != -1) { // Make sure the value exists
            this.splice(index, 1);
        }
    };

并尝试

tags.spliceObject(selectedrow);

答案 1 :(得分:0)

使用HTML中的$ index访问数组的索引。供参考:https://docs.angularjs.org/api/ng/directive/ngRepeat

而不是在选项标签上使用ng-repeat,您可以使用angular提供的ng-options指令。参考:https://docs.angularjs.org/api/ng/directive/ngOptions