Can't set selected value of ng-options

后端 未结 4 484
自闭症患者
自闭症患者 2021-02-02 15:28

I am trying to populate a drop-down select options list and set a default selected value using ng-model and ng-options.

I have the following code in my view:

<         


        
4条回答
  •  一个人的身影
    2021-02-02 16:12

    This isn't the same thing because objects in javascript are passed by reference.

    If you take the first example:

    $scope.siteList = [
        { id: 1, name: 'cycling'},
        { id: 2, name: 'walking'},
        { id: 3, name: 'holidays'}
    ]
    
    $scope.thisTour.site = { id: 2, name: 'walking'};
    

    Then you do this:

    $scope.thisTour.site.id = 3;
    console.log($scope.siteList[1].id) // 2
    

    In other words, whilst your two objects are equal in value, they aren't the same object. The ngOptions directive sees this, so would set thisTour.site to a blank value because it isn't one of the allowed options.

    Google "passing by reference in javascript" to learn more.

提交回复
热议问题