【问题标题】:How do I insert HTML code that references directives?如何插入引用指令的 HTML 代码?
【发布时间】:2014-05-09 08:09:57
【问题描述】:

由于 IE8 的性能问题,我需要通过 html 插入选择。但我需要插入的 select 语句具有 Angular 指令,例如 ng-model 和 ng-change。当我运行插入选择的代码时,选择会按预期显示,但是诸如 ng-change 之类的指令属性不起作用。我通过设置innerHTML插入的代码是这样的:

<select ng-model='currentAccounts' ng-change='selectedAccountChanged()' >
      <option value='1'>option 1</option>
      <option value='2'>option 2</option>
</select>

如何让这些指令生效?

更新:要清楚我在这里所做的是生成上述选择的代码。

  webServices.getAccounts()
  .then(function (result) {
    var str = "<select ng-model='currentAccounts' ng-change='selectedAccountChanged()' id='" + CHARGE_NUM_CONTROL_ID + "' style='width: 100%;' size='17' >";
     for (var i = 0; i < numAvailAccounts; i++) {
         str += "<option value='" + i + "'";
         if (i == 0) {
            str += " selected";       // select the 1st item
         }
         str += ">" + $scope.availableAccounts[i].Name + "</option>";
     }
     str += "</select>";
     ChargeNumPH.innerHTML = str;  // load all the options at once
  })

这段代码更新了以下Div的内容。

<div id="ChargeNumPH"></div>

(FWIW, I need the ng-change because when an item is selected it needs to appear in a string that displays the items selected.)

附言。以这种方式插入代码非常快。我能够显示一个包含 1500 个项目的选择 在 50 毫秒内。使用 ng-option 和 IE8 需要 9,000 毫秒。

【问题讨论】:

  • 你使用指令吗?你能再显示一些代码吗?
  • 添加了选择生成代码。

标签: html angularjs internet-explorer-8 angularjs-directive


【解决方案1】:

ng-model 和 ng-change 仍然应该使用这种方法很好地连接起来。您可以使用 ng-repeat 生成选项列表,但它仍然可能导致您的性能问题。

<select ng-model='currentAccount' ng-change='selectedAccountChanged()'>
  <option ng-repeat="account in currentAccounts" value="{{account.value}}">{{account.text}}</option>
</select>

**我将 ng-model 更改为 currentAccount 并将 currentAccounts 设为查找数组。

function TestController($scope) {
  $scope.currentAccount = 1;

  $scope.currentAccounts = [
    { value: 1, text: 'option 1' },
    { value: 2, text: 'option 2' }
  ];

  $scope.selectedAccountChanged = function () {
    alert('currentAccount changed to ' + $scope.currentAccount);
  };
}

http://codepen.io/jessebibee/pen/bCvLG

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2018-06-04
    • 2017-09-24
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多