簡體   English   中英

如何在指令中使用innerHTML插入的html上使用ng-bind

[英]How to use ng-bind on html that is inserted with innerHTML inside a directive

我做了一個自定義指令,里面有兩個ng-repeats 一個ng-repeat嵌套在另一個里面。 我讓代碼正常工作,它在 chrome 中運行良好,但在 iPad 和 iPhone 上運行緩慢。

有 10 個部分,每個部分有 5 行,在滾動和更改綁定時需要非常快。 我認為減速來自通過綁定的所有循環,但在用戶輸入時只需要更改一個數組。 頁面加載后,其余的綁定永遠不會改變。

所以我試圖找出一種方法來加載嵌套的無序列表,同時只綁定一個變量。 這是我的指令的偽代碼。

.directive('myDirective', function($compile) {
  return {
    restrict: 'A'
    link: function(scope, elm, attrs) {
      outerList = '<ul><li>statically generated content that does not change'
      outerList += '<ul><li ng-bind="I only need to bind one thing"><li></ul>'
      outerList += < /ul>'
      elm[0].innerHTML = outerList
    }
  }
});

如您所見,我正在嘗試生成 html 內容,然后使用 innerHTML 將其插入。 問題是當我這樣做時ng-bind不起作用。 我試圖再次$compile它,但這並沒有改變任何東西。

有沒有人有更好的方法? 我不在乎解決方案有多可怕,我只是真的需要應用程序的這部分超級快。 最主要的是我不想要ng-repeat除非有辦法讓它在加載時做它的事情,然后再也不循環任何東西。

我想以最有可能的 Angular 方式來做這件事,但我意識到我可能不得不做一些完全違背 Angular 哲學的事情

下面是一個示例,說明如何修改代碼以便從指令外部的作用域綁定指令中的某個變量。 我已經使用$compile來確保您的指令 DOM 操作有自己編譯的指令。 我已經使用replaceWith用你編譯的 DOM 替換指令元素:

HTML

<div ng-app="myApp">
    <div ng-controller="ctrlMain">
        <div my-directive="bindMe"></div>
    </div>
</div>

JavaScript

var app = angular.module('myApp',[]);
app.controller('ctrlMain',function($scope){
    $scope.bindMe = {id:1,myvar:"test"};
});
app.directive('myDirective', function($compile){
  return{
    restrict: 'A',
    scope: {
        varToBind: '=myDirective'     
    },
    link: function(scope, elm, attrs){
      outerList = '<ul><li>statically generated content that does not change'
      outerList += '<ul><li ng-bind="varToBind.myvar"><li></ul>'
      outerList += '</ul>';
      outerList = $compile(outerList)(scope);
      elm.replaceWith(outerList);
    }
  }
});

這是一個演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM