How to conditionally apply a template via custom Angular directives?

后端 未结 6 810
攒了一身酷
攒了一身酷 2020-12-29 02:37

DEMO

Consider the following directive:

angular.module(\'MyApp\').directive(\'maybeLink\', function() {
  return {
    replace: true,
    s         


        
6条回答
  •  天命终不由人
    2020-12-29 03:08

    I came up with the following version at the end:

    angular.module('MyApp').directive('maybeLink', function($compile) {
      return {
        scope: {
          maybeLink: '=',
          maybeLinkText: '='
        },
        link: function(scope, element, attrs) {
          scope.$watch('maybeLinkText', function(newText) {
            scope.text = newText.replace(/\n/g, '
    '); }); scope.$watch('maybeLink', function() { var newElement; if (scope.maybeLink) { newElement = $compile('')(scope); } else { newElement = $compile('')(scope); } element.replaceWith(newElement); // Replace the DOM element = newElement; // Replace the 'element' reference }); } }; });

提交回复
热议问题