AngularJS - 怎样一个包含数据绑定模板内更改元素? [英] AngularJS - How do I change an element within a template that contains a data-binding?

查看:115
本文介绍了AngularJS - 怎样一个包含数据绑定模板内更改元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是模板使用动态变量名称角最推荐的方法?

What is the most Angular recommended way to use a dynamic tag name in a template?

我有一个包含H1-H6标签下拉。用户可以选择任何这些和内容将改变到由所选标题标签(其被存储在$范围)被包装。的内容被绑定到模型即内{{}}

I have a drop-down containing h1-h6 tags. A user can choose any of these and the content will change to being wrapped by the chosen header tag (which is stored on the $scope). The content is bound to the model i.e. within {{ }}.

要坚持结合我可以改变的标记和使用$编译。但是,这并不工作,因为它被附加(显然)角代替{{}}与模型值之前。它H3在页面加载。

To persist the binding I can change the markup and use $compile. However, this does not work because it gets appended (obviously) before Angular replaces the {{ }} with model values. It's h3 on page load.

例如:

<div id="root">
    <h3 id="elementToReplace">{{ modelData }}</h3>
</div>

当重新编译我已经使用字符串尝试如下:

When re-compiling I have tried using a string as follows:

<{{ tag }} id="elementToReplace">{{ modelData }}</{{ tag }}>

任何想法?

推荐答案

演示Plunker这里

定义一个名为标记的范围的变量,并将其绑定到这两个选择列表和自定义指令。

Define a scope variable named 'tag' and bind it to both your select list and custom directive.

HTML

     <select ng-model="tag" ng-init="tag='H1'">
           <option ng-value="H1">H1</option>
           <option ng-value="H2">H2</option>
           <option ng-value="H3">H3</option>
           <option ng-value="H4">H4</option>
           <option ng-value="H5">H5</option>
     </select> 
     <tag tag-name="tag">Hey There</tag>

接下来,通过标记范围模型转化为使用双向模型绑定您的指令:

Next, pass the tag scope model into your directive using two-way model binding:

  var app = angular.module('app',[]);
  app.directive('tag', function($interpolate) {
      return  {
         restrict: 'E',
         scope: {
             tagName: '='
         },
         link: function($scope, $element, $attr) {
            var content = $element.html();
            $scope.$watch('tagName', function(newVal) {
                 $element.contents().remove();
                 var tag = $interpolate('<{{tagName}}>{{content}}</{{tagName}}>')
                       ({tagName: $scope.tagName, content: content});
                 var e = angular.element(tag);
                 $element.append(e);
            });
         }
      }
  });

请注意,在自定义的指令,我们使用$插值服务生成基于在选择列表中选择标签的HTML元素。一个$手表功能用于监视更改标签模型,当它发生变化,新的元素添加到DOM。

Notice that in the custom directive, we are using the $interpolate service to generate the HTML element based on the Tag that was selected in the select list. A $watch function is used to watch for changes to the tag model, and when it changes, the new element is appended to the DOM.

这篇关于AngularJS - 怎样一个包含数据绑定模板内更改元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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