【问题标题】:Appending templates when ng-clickng-click 时附加模板
【发布时间】:2015-08-06 02:11:40
【问题描述】:

我有一个按钮供用户点击的情况。点击按钮后,会创建一个新的<div>(实际上是一个具有隔离范围的模板),并将这个<div>附加到现有元素上,如下所示:

<button ng-click="openNewDiv()"></button>
<div>Div content for DIV 1</div>
<div>Div content for DIV 2</div>
<div>Div content for DIV 3</div>
<div>Div content for DIV 4</div>

每个&lt;div&gt;共享相同的模板和逻辑,具有孤立的范围,当用户单击按钮时,DIV4旁边会附加第五个&lt;div&gt;,这也与上述4个&lt;div&gt;共享相同的逻辑的,我怎样才能在 AngularJS 中实现这一点?我正在阅读这篇文章以找到解决方案,我的方向是否正确?

http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx

【问题讨论】:

    标签: javascript angularjs compilation


    【解决方案1】:

    这可以使用指令see here for the docs 来实现。您可以创建一个包含&lt;div&gt; 元素的模板和逻辑的指令。至于在单击按钮时多次添加此指令,您可以使用 ngRepeat 迭代包含指令数据的数组。

    在您的控制器中:

    $scope.myData = [dataDiv1, dataDiv2, ..., dataDivx];
    $scope.openNewDiv = function() {
        $scope.myData.push(anotherDataDiv);
    };
    

    在你看来:

    <button ng-click="openNewDiv()"></button>
    <my-directive myData="data" ng-repeat="data in myData"></my-directive>
    

    【讨论】:

    • 非常感谢您的澄清,我想知道 $compile 服务是否适合我的情况,所以在这种情况下 $compile 不是必需的?
    • 我会使用 link 函数而不是 compile 函数作为您的指令。 See this post for more info
    • 我很好奇什么时候应该使用 $compile,从我的搜索来看,$compile 是将新制作的 DOM 编译为现有的,这在某种程度上符合我的情况
    • linkcompile 之间的最大区别在于compile 只被调用一次,而不管指令是否有多个副本(在我们的例子中是 ng-repeat)。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2015-12-17
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多