What are the differences between ng-repeat and ng-options and why do they not behave the same way?

后端 未结 5 990
盖世英雄少女心
盖世英雄少女心 2020-11-27 20:31

How do ng-options and ng-repeat differ?

In the following code, I have an ng-repeat that iterates through a list of people:

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 20:43

    From the documentation:

    Note: ngOptions provides an iterator facility for the element which should be used instead of ngRepeat when you want the select model to be bound to a non-string value. This is because an option element can only be bound to string values at present.

    This fiddle makes the point more clear: select2 will bind to select 1 but not the other way around. Click the buttons and the reason will reveal itself :-)

    HTML

    selected: {{selectedPerson}} {{typeofSelectedPerson()}}

    JS

    function MyCtrl($scope){
        $scope.selectedPerson = 1;
        $scope.people = [
            {
                id: 1,
                name: 'Ze'
            },
            {
                id: 2,
                name: 'Jao'
            }
        ];
    
        $scope.typeofSelectedPerson = function(){
            return typeof $scope.selectedPerson;
        }
    }
    

提交回复
热议问题