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

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

问题描述

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

在这里玩耍

解决方案

这是我的方法.几件事:-

1) 创建一个子作用域而不是 myMarkup 上的隔离作用域,最终实际指令 myInput 将被隔离.如果您确实需要在同一范围内支持多个 myMarkup 指令,则需要这样做.

2) 你需要在按钮上有一个点击事件,我不会在标记上做逻辑,而是抽象到作用域上的一个方法.

3) 你只需要一个按钮,不需要 2 个按钮.只需更改按钮的文本即可.

.directive('myMarkup', function($compile) {返回 {限制:'A',scope: true,//创建子作用域编译:函数(元素){//只需要一个按钮var showButton = '<button ng-click="toggleMarkup()">{{model.showMarkup ?"Hide": "Show"}} 标记</button>';var markup = '<pre ng-show="model.showMarkup">'+ escapeHtml(element.html()) + '</pre>';//附加标记element.append(showButton).append(markup);返回链接器;}};功能链接器(范围,元素){范围.模型 = {显示标记:假};//单击按钮上的事件处理程序以切换标记scope.toggleMarkup = function(){scope.model.showMarkup = !scope.model.showMarkup;}};});

演示

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.

So, this:

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

should result in this:

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

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

Here is my attempt to implement this.

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

PLAYGROUND HERE

解决方案

Here is my approach. Couple of things:-

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) 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) 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天全站免登陆