AngularJS:如何实现输出其标记指令? [英] AngularJS: How to implement a directive that outputs its markup?

查看:177
本文介绍了AngularJS:如何实现输出其标记指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<大骨节病> DEMO

想象一下,我有一些标记,例如:

Imagine I have some markup, e.g.:

<my-input model="data.firstName"></my-input>

现在,我想创建一个我的标记指令,将添加一个按钮来显示/隐藏它的标记。

Now, I would like to create a my-markup directive that will add a button to show/hide its markup.

所以,这样的:

<div my-markup>
  <my-input model="data.firstName"></my-input>
</div>

应导致这样的:

和被点击的按钮时,标记应当如下:

and when the button is clicked, the markup should appear:

我的标记指令不应该打破其子女的任何数据绑定。

The my-markup directive should not break any data bindings of its children.

这是我尝试实现这一点。

出现的标记,但按钮不起作用。任何想法如何解决这一问题?

The markup appears, but the button doesn't work. Any ideas how to fix this?

<大骨节病> 操场这里

推荐答案

下面是我的做法。事情夫妇: -

Here is my approach. Couple of things:-

1),而不是对myMarkup隔离范围,创建一个子范围,最终的实际指令 myInput 将被隔离。如果你确实需要支持在同一范围的多个 myMarkup 指令这是必需的。

1) Instead of isolated scope on myMarkup, create a child scope, ultimately the actual directive myInput will be isolated. This would be required if you do need to support multiple myMarkup directive under the same scope.

2)您需要在按钮上单击事件,我不会做逻辑上的标记,而不是抽象出对范围的方法。

2) You need a click event on the button, i wouldn't do logic on the markup instead abstract out to a method on the scope.

3)您将只需要一个按键,不需要2个按钮。只是改变了按钮的文本。

3) You would just need one button, do not need 2 buttons. Just change the text of the button.

.directive('myMarkup', function($compile) {


  return {
    restrict: 'A',
    scope: true, //Create a child scope
    compile: function(element) {
      //Just need one button
      var showButton = '<button  ng-click="toggleMarkup()">{{model.showMarkup ? "Hide": "Show"}} Markup</button>';
      var markup = '<pre ng-show="model.showMarkup">' + escapeHtml(element.html()) + '</pre>';

      //append the markups
      element.append(showButton).append(markup);

      return linker;
     }
   };

    function linker(scope, element) {
        scope.model = {
          showMarkup: false
        };
        //Click event handler on the button to toggle markup
        scope.toggleMarkup = function(){
          scope.model.showMarkup = !scope.model.showMarkup;
        }
    };
});

演示

Demo

这篇关于AngularJS:如何实现输出其标记指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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