Select元素的奇怪行为取决于DOM顺序

时间:2015-05-05 15:46:48

标签: angularjs

这是我的控制器:

angular.module('myApp.controllers', [])
    .controller('Controller1', function($scope) {
        $scope.selected_country = "";
        $scope.countries = [{
            id: 'US',
            desc: 'United States'
        }, {
            id: 'GB',
            desc: 'United Kingdom'
        }];
    });

这是一个有效的HTML:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
</head>
<body ng-controller="Controller1">

  <div>Selected Country: {{selected_country}} </div>

  <form name="myForm">
    <select name=country" ng-model="selected_country"
            ng-options="country.id as country.desc for country in countries"
    </select>
  </form>

  <script src="bower_components/angular/angular.js"></script>
  <script src="app.js"></script>
  <script src="controllers.js"></script>
</body>
</html>

但如果我将<div>放在<select>之后:

  <form name="myForm">
    <select name=country" ng-model="selected_country"
            ng-options="country.id as country.desc for country in countries"
    </select>
  </form>

  <div>Selected Country: {{selected_country}} </div>

<div>刚从浏览器中消失。为什么呢?

1 个答案:

答案 0 :(得分:3)

您缺少引号和尖括号。

<select name=country" ng-model="selected_country"
        ng-options="country.id as country.desc for country in countries"

应该是

<select name="country" ng-model="selected_country"
            ng-options="country.id as country.desc for country in countries">