data-ng-bind 不适用于 <option> 元素

data-ng-bind does not work with <option> element

我刚开始学习 angular,但遇到了这个问题。我在 AngularJS : Why ng-bind is better than {{}} in angular? 上读到 {{}}ng-bind 会给你相同的结果。但是,以下代码并非如此:

JS

(function () {
    angular
        .module("myApp", [])
        .controller("selectCtrl2", function ($scope, $http) {
            $http({
                method: "GET",
                url: "http://localhost/testService/name.php"
            })
            .then(function (response) {$scope.names = response.data.content;},
             function (response) {$scope.names = response.statusText;});
        });
})();

HTML

<body data-ng-app="myApp">
    <div data-ng-controller="selectCtrl2">
        <select>
            <option data-ng-repeat="x in names">
                <span data-ng-bind="x"></span>
            </option>
        </select>
    </div>
</body>

ng-repeat 实际上创建了 3 个选项标签,但它们的内部 HTML 只是空格。 由于某些奇怪的原因,如果我使用 {{x}},它们的内部 HTML 将填充我准备的数组 [a, b, c] 中的文本。请问是什么原因。

来自the answer by Konstantin Krass

This ng-bind is a directive and will place a watcher on the passed variable. So the ng-bind will only apply, when the passed value does actually change.

The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary. 1

更新:

主要原因已在 by georgeawg

中解决

1

<option> 中包含 <span> 元素是非法的 HTML <option> elements.The 只允许内容为文本。

移动 ng-bind directive to the <option> element 即可。

演示

<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app>
    <div ng-init="names=['fred','sam','jane']">
     
        <select>
            <!-- ILLEGAL HTML
            <option data-ng-repeat="x in names">
                <span data-ng-bind="x"></span>
            </option>
            -->

            <!-- PERMITTED -->
            <option data-ng-repeat="x in names" ng-bind="x">
            </option>
        </select>
    </div>
  </body>

带有 ng-bind directive as part of the <option> element, the directive will insert only the text result of the Angular Expression 是合法的 HTML 和允许的内容。

来自 MDN 文档:

The HTML <option> element is used to define an item contained in a <select>, an <optgroup>, or a <datalist> element. As such, can represent menu items in popups and other lists of items in an HTML document.

Content categories   None.
Permitted content    Text, possibly with escaped characters (like `&eacute;`).

— MDN HTML Element Reference - <option>

另见,