如何通过自定义Angular指令有条件地应用模板? [英] How to conditionally apply a template via custom Angular directives?

查看:64
本文介绍了如何通过自定义Angular指令有条件地应用模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

演示

请考虑以下指令:

angular.module('MyApp').directive('maybeLink', function() {
  return {
    replace: true,
    scope: {
      maybeLink: '=',
      maybeLinkText: '='
    },
    template: '<span>' + 
              '  <span ng-hide="maybeLink" ng-bind-html="text"></span>' +
              '  <a ng-show="maybeLink" href="#" ng-bind-html="text"></a>' +
              '</span>',
    controller: function($scope) {
      $scope.text = $scope.maybeLinkText.replace(/\n/g, '<br>');
    }
  }; 
});

该指令将<span><a>都添加到DOM(一次只能看到一个).

The directive adds both the <span> and the <a> to the DOM (only one is visible at a time).

我该如何重写指令,以便将 <span><a> 添加到DOM中,但不能同时添加两者?

How could I rewrite the directive such that it will add either <span> or <a> to the DOM, but not both?

更新

好的,我想我可以这样使用ng-if:

OK, I guess I could use ng-if like that:

template: '<span>' + 
          '  <span ng-if="!maybeLink" ng-bind-html="text"></span>' +
          '  <a ng-if="maybeLink" href="#" ng-bind-html="text"></a>' +
          '</span>'

但是,在这种情况下,如何摆脱周围的<span>?

But, how could one get rid of the surrounding <span> in this case?

更新2

这里是使用$compile的指令的版本.它没有周围的<span>,但是两种方式的数据绑定也不起作用.我真的很想知道如何解决双向数据绑定问题.有什么想法吗?

Here is a version of the directive that uses $compile. It doesn't have the surrounding <span>, but the two way data binding doesn't work either. I'm really interested to know how to fix the two way data binding issue. Any ideas?

演示

angular.module('MyApp').directive('maybeLink', function($compile) {
  return {
    scope: {
      maybeLink: '=',
      maybeLinkText: '='
    },
    link: function(scope, element, attrs) {
      scope.text = scope.maybeLinkText.replace(/\n/g, '<br>');

      if (scope.maybeLink) {
        element.replaceWith($compile('<a href="#" ng-bind-html="text"></a>')(scope));
      } else {
        element.replaceWith($compile('<span ng-bind-html="text"></span>')(scope));  
      } 
    } 
  }; 
});

推荐答案

您也许可以使用template 功能.根据文档:

You might be able to use a template function. According to the docs:

您可以将template指定为代表模板的字符串,或者指定为函数,该函数接受两个参数tElement和tAttrs(在下面的编译函数api中进行描述),并返回代表模板的字符串值.


function resolveTemplate(tElement, tAttrs) {

}

angular.module('MyApp').directive('maybeLink', function() {
  return {
    //...
    template: resolveTemplate,
    //...
  }; 
});

这篇关于如何通过自定义Angular指令有条件地应用模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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