Pregunta

I created an Angular directive to provide a means of attaching an ng-if directive and erase the element, replacing it with its content. I think this should be much easier, possibly using transclusion, but I can't quite work it out. How should I do this?

angular.module('myApp', []).
directive('tyReplace', function () {
    return {
        restrict: 'A',
        replace: true,
        scope: { tyReplace: '@' },
        link: function (scope, element) {
            element.parent().text(scope.tyReplace);
        }
    }
});

Usage:

<td>
    <div ty-replace="{{content}}" ng-if="condition"></div>
    <ul ng-if="othercondition">
        <li ng-repeat="item in items">{{item}}</li>
    </ul>
</td>

I started adding additional display options within the <td>, but we also allow certain cells to be edited by toggling the contenteditable attribute. This approach allows me to continue providing that option.

EDIT

Very soon, I would like to be able to replace {{content}} with something more complex, such as an <input type="text" /><input type="datetime" /> for text and date controls when editing. The current solution won't work when I want more complex markup inside.

¿Fue útil?

Solución

UPDATED

Using transclusion in your directive provides you with options for manipulating the DOM with access to the transcluded content in the compile/link function. There, you may use jqLite to overwrite the contents of the parent with the contents of the clone:

JavaScript:

angular.module('myApp', [])
.controller('MyController', function($scope){
  $scope.condition = true;
  // $scope.othercondition = true;
  $scope.items = [1, 2, 3, 4];
  $scope.obj = {
    name: ''
  };
})
.directive('myDirective', function(){
  return {
    transclude: true,
    replace: true,
    template: '<div ng-transclude></div>',
    compile: function(tElem, tAttrs, transclude) {
      return {
        pre: function(scope, element) {
          transclude(scope, function(clone){
            element.parent().empty().append(clone);
          });
        }
      }
    }
  }
});

index.html:

<td>
  <div ng-if="condition" my-directive ><input type="text" ng-model="obj.name" /></div>
  <ul ng-if="othercondition">
    <li ng-repeat="item in items">{{item}}</li>
  </ul>
</td>

Plunker Demo

Otros consejos

I have created a Plunker that seems to work OK.

Is this what you are looking for in the behavior?

I feel like such a goof. See this Plunker. Turns out I just wanted ng-transclude.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top