【问题标题】:data-ng-bind does not work with <option> elementdata-ng-bind 不适用于 <option> 元素
【发布时间】:2017-06-11 19:35:42
【问题描述】:

我刚刚开始学习 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 个选项标签,但它们的 innerHTML 只是空格。 由于一些奇怪的原因,如果我使用 {{x}},它们的 innerHTML 将被我准备的数组中的文本填充 [a, b, c]。我想知道可能是什么原因。

【问题讨论】:

    标签: javascript html angularjs ng-bind


    【解决方案1】:

    &lt;option&gt; 元素中包含&lt;span&gt; 元素是非法的HTML。唯一允许的内容是文本。

    ng-bind directive 移动到&lt;option&gt; 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 作为&lt;option&gt; element 的一部分,该指令将仅插入Angular Expression 的文本结果,这是合法的HTML 和允许的内容。

    来自 MDN 文档:

    HTML &lt;option&gt; 元素用于定义包含在 &lt;select&gt;&lt;optgroup&gt;&lt;datalist&gt; 元素中的项目。因此,可以表示弹出窗口中的菜单项和 HTML 文档中的其他项目列表。

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

    — MDN HTML Element Reference - &lt;option&gt;

    另见,

    【讨论】:

      【解决方案2】:

      来自the answer by Konstantin Krass

      这个ng-bind 是一个指令,它会在传递的对象上放置一个观察者 多变的。因此,ng-bind 仅适用于 传递的值 实际改变

      另一方面,括号将被脏检查并刷新 每个 $digest,即使它没有必要1

      更新:

      主要原因由georgeawgthe answer解决


      1https://stackoverflow.com/a/23382400/1575353

      【讨论】:

      猜你喜欢
      • 2014-09-19
      • 2014-02-06
      • 2014-07-16
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多