Angularjs: select not updating when ng-model is updated

前端 未结 5 2016
我在风中等你
我在风中等你 2020-12-08 18:32

I\'ve created the following example so you can see exactly what is happening: http://jsfiddle.net/8t2Ln/101/

The same thing happens if I use ng-options. I have a d

5条回答
  •  心在旅途
    2020-12-08 18:59

    The problem is that, since you're not using ng-options the browser had not finished rendering at the point when you set the new selectedDevice. If you're set on on using ng-options you can use this workaround. Use $timeout to wrap your $scope.selectedDevice = newElem.value; to ensure it runs after the browser has finished rendering the changes with ng-repeat.

    I also added code to increment the next value on successive adds because hardcoding it to '3' meant that the third option would continually be selected even when more are added.

    var testApp = angular.module('testApp', ['ngRoute']);
    
    testApp.controller('Ctrl', function($scope, $timeout) {
    
      $scope.newInput = '';
      $scope.inputDevice = [{
        value: '1',
        label: 'input1'
      }, {
        value: '2',
        label: 'input2'
      }];
      $scope.selectedDevice = '';
    
      $scope.addType = function() {
        var last = Number($scope.inputDevice[$scope.inputDevice.length - 1].value) + 1;
        var newElem = {
          label: $scope.newInput,
          value: last.toString()
        };
        $scope.inputDevice.push(newElem);
        $timeout(function() {
          $scope.selectedDevice = newElem.value;
        }, 0);
      };
    
    });
    
    
    
    


    {{ selectedDevice }}

提交回复
热议问题