如何使用NG单击链接调用指令范围内? [英] How do I use ng-click in link call within a directive?

查看:110
本文介绍了如何使用NG单击链接调用指令范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://plnkr.co/edit/Ry8gkozAaudhlmdPPQie?p=$p$ PVIEW

正如你可以在plunkr看到的,我想创建一个指令,它会根据该指令元素的属性的presence渲染不同的模板。

 <我-DIR>< /我-DIR>
<我-DIR someparam =真正的>< /我-DIR>

我通过把条件指令的链接调用内像这样

  VAR海峡=;
        如果(attr.someparam){
          海峡=<按钮类='BTN BTN-警告'NG点击='test2的()'>测试2版; /按钮>中;
        }其他{
          海峡=<按钮类='BTN BTN-小学'NG点击='test1的()'>试验1 LT; /按钮>中;
        }
        el.append(STR);

我不希望使用 NG-如果,因为如果模板不被渲染的,我不希望HTML在页面上存在所有

这似乎是有点工作,但 NG-点击通话似乎没有在所有的工作。请让我知道我做错了,如果有做同样的一个更好的/正确的方法。


解决方案

您已经编译你的HTML,你是能够使用$范围以动态添加HTML。

在$编译功能将你的HTML绑定到$范围。这是一个链接功能。如果没有这个角度无法找到模板的指令就像NG-点击。

http://plnkr.co/edit/vfVeAkGO5VaJd2dWUTWV?p=$p$ PVIEW

  .directive('MYDIR',函数($编译){
返回{
  限制:'E',
  链接:功能($范围,萨尔瓦多,ATTR,CNTL){
    无功海峡=;
    如果(attr.someparam){
      海峡=<按钮类='BTN BTN-警告'NG单击= test2的()>测试2版; /按钮>中;
    }其他{
      海峡=<按钮类='BTN BTN-小学'NG点击='test1的()'>试验1 LT; /按钮>中;
    }
    VAR elmnt = $编译(STR)($范围内);
    el.html(); //虚拟清
    el.append(elmnt);
  }
};

http://plnkr.co/edit/Ry8gkozAaudhlmdPPQie?p=preview

As you can see in that plunkr, I am trying to create a directive which will render different templates depending on presence of attributes on that directive element.

<my-dir></my-dir>
<my-dir someparam="true"></my-dir>

I am doing this by putting the conditions within the directive's link call like:

var str = "";
        if(attr.someparam){
          str = "<button class='btn btn-warning' ng-click='test2()'> Test 2 </button>";
        }else{
          str = "<button class='btn btn-primary' ng-click='test1()'> Test 1 </button>";
        }
        el.append(str);

I don't want to use ng-if, because if the template is not to be rendered, I don't want the html to exist on the page at all.

This seems to be somewhat working, but the ng-click calls don't seem to be working at all. Please let me know what I am doing wrong and if there is a better/proper way of doing the same.

解决方案

You've to compile your html, for you to be able to use the $scope with a dynamically added HTML.

The $compile function will bind your HTML to the $scope. It's a linking function. Without this angular cannot find the directives in your template like ng-click.

http://plnkr.co/edit/vfVeAkGO5VaJd2dWUTWV?p=preview

 .directive('myDir', function($compile) {
return {
  restrict: 'E',
  link: function($scope,el,attr,cntl){
    var str = "";
    if(attr.someparam){
      str = "<button class='btn btn-warning' ng-click=test2()> Test 2 </button>";
    }else{
      str = "<button class='btn btn-primary' ng-click='test1()'> Test 1 </button>";
    }
    var elmnt = $compile(str)($scope);
    el.html(""); // dummy "clear"
    el.append( elmnt );
  }
};

这篇关于如何使用NG单击链接调用指令范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆