2016-09-09 41 views
10

我的自定义指令模板中的自动递增编号有问题。我需要的功能是在按钮点击上添加动态HTML内容。自定义指令中的自动递增值

main.html中
<div class="addTemplateContainer{{dataPoint.id}}"></div> <div ant-add-template-button parent="addTemplateContainer{{dataPoint.id}}"></div>

指令 - 蚂蚁插件模板button.js

app.directive('antAddTemplateButton', function ($compile) { 
return { 
    restrict: 'A', 
    link: function (scope, element, attrs) { 
     $(element).on('click', function() { 
      var compiledeHTML = $compile('<div ant-add-template></div>')(scope); 
      $('div.' + attrs.parent).append(compiledeHTML); 
     }); 
    } 
}}); 

指令 - 蚂蚁附加template.js

app.directive('antAddTemplate', function() { 
return { 
    restrict: 'A', 
    link: function (scope, element, attrs) { 

    }, 
    templateUrl: '../html/relation-join.html' 
}}]); 

模板 - my-template.html

<select ng-model="joins[$i]" ng-change="myFunc($i)"></select> 

上面的代码适用于添加HTML内容,但我需要使用数组为我的ng模型用于选择&有一些功能,我需要调用每个更改事件的函数。我无法找到每次单击按钮时将$ i作为增量值的方法。
它应该有ng-models作为连接[0],连接[1],连接[2]等。更具体地说,我不想在这里使用隔离范围。

任何帮助,将不胜感激。

+1

我不太明白你在做什么用例试图解决,但这种尝试解决方案似乎非常复杂。如果您需要动态添加组件,您只需要“ng-repeat”,并且可以触发某项添加到重复数据。 – RIAstar

+0

@RIAstar我已经做了同样的事情,但我期待它应该能够处理更易于管理的指令。谢谢...! $ window甚至为我的链接功能工作,但没有为模板工作。 – ba1ar

回答

-1

你可以试试这个,NG点击会先启用,然后纳克变化将被解雇

1

我相信你会需要实现的antAddTemplatecompile功能,以操纵模板就被编译之前。

喜欢的东西:

app.directive('antAddTemplate', function() { 
return { 
    restrict: 'A', 
    compile: function(element, attrs) { 
     // dynamically set the ng-model attribute by using the index supplied 
     element.find('select') 
      .attr('ngModel', 'joins['+attrs.index+']') 
      .attr('ngChange', 'myFunc('+attrs.index+')'); 

     // return the link function (the function that would be declared with link: property when compile: is not being used) 
     return function linkFunction (scope, element, attrs) { 

     }; 
    }, 
    templateUrl: '../html/relation-join.html' 
}}]); 

现在,我们需要通过索引到ant-add-template,所以更新ant-add-button做到这一点:

app.directive('antAddTemplateButton', function ($compile) { 
return { 
    restrict: 'A', 
    link: function (scope, element, attrs) { 
     $(element).on('click', function() { 
      // add a new index to the joins array 
      var index = scope.joins.push() - 1; 

      // compile ant-add-template with an index attribute 
      var compiledeHTML = $compile('<div ant-add-template index="'+index+'"></div>')(scope); 
      $('div.' + attrs.parent).append(compiledeHTML); 
     }); 
    } 
}}); 
+0

我还没有尝试过以上,但我已经完成了几乎相同的工作,但我想提请你注意,我需要在我的模板html页面中我的ng-change功能的索引,我无奈 – ba1ar

+0

ok,updated也可以用索引来设置ngChange属性。还有另一个你需要它的地方吗? – plong0

+0

不,只有一次,因为我在我的问题中提到 – ba1ar