Empty first element in dropdown list

后端 未结 6 2075
花落未央
花落未央 2020-12-25 10:59

I am quite a beginner with AngularJS and currently I am working on a web application in Django where I use AngularJS for the frontend part i can say. My problem is that the

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-25 11:25

    Here's some code directly from the AngularJs.org website about select lists:

    
    

    First, as you can see, you don't need to use the ng-repeat to build your options list. Angular is going to basically let you do a foreach loop on a collection to build your option list. Second, you have the ng-model which is on the select, but isn't the same as your collections name. This is going to be your item which is actually collected at post time .

    function MyCntrl($scope) {
       $scope.colors = [
          {name:'black', shade:'dark'},
          {name:'white', shade:'light'},
          {name:'red', shade:'dark'},
          {name:'blue', shade:'dark'},
          {name:'yellow', shade:'light'}
      ];
      $scope.color = $scope.colors[2]; // red
    }
    

    Okay, and here's the javascript controller code. $scope.colors is the collection and $scope.color is the model property which has been assigned to the select list in the html. As you can see from this example the model property is being given a default starting value of the third option in the array. For you, this can be set from the http.get you're using for loading up your page initally.

    Now when you're doing the foreach, you're basically grabbing the 'name' value from the collection and you're saying 'show this value' in the dropdown and use this value on the post. By having that inital model property set, you should be able to avoid having an empty option field in your drop down list.

    Reference: AngularJS Select

提交回复
热议问题