【问题标题】:How to use ng-bind on html that is inserted with innerHTML inside a directive如何在指令内插入innerHTML的html上使用ng-bind
【发布时间】:2013-06-14 03:25:57
【问题描述】:

我创建了一个自定义指令,其中包含两个 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 哲学的事情

【问题讨论】:

  • 你想要一些重复但又不想使用 ngRepeat 的东西,这绝对不是“最有角度的方式”;)但你有你的理由,所以有人会帮助你。在此之前,您能否创建 fiddle 来演示什么是有效的(但速度很慢),什么是无效的?
  • 目前还不清楚您希望它如何运行。 this fiddle 对你有用吗?如果没有,你能解释一下它缺少什么吗?
  • 对不起,我不是很清楚。我正要使用指向小提琴的链接来更新它。您的解决方案正是我正在寻找的,所以现在不需要了。非常感谢。
  • 太好了,我把它作为答案发布了

标签: javascript angularjs angularjs-directive angularjs-ng-repeat angularjs-compile


【解决方案1】:

这里是一个示例,说明如何修改代码以便在指令之外的范围内绑定指令中的某些变量。我已经使用$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);
    }
  }
});

Here is a demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多