javascript - 简单的 AngularJS 替换指令

标签 javascript angularjs angularjs-directive

我创建了一个 Angular 指令来提供一种方法来附加 ng-if 指令并删除该元素,用其内容替换它。我认为这应该更容易,可能使用嵌入,但我无法完全解决。我应该怎么做?

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

用法:

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

我开始在 <td> 中添加额外的显示选项, 但我们也允许通过切换 contenteditable 来编辑某些单元格属性。这种方法使我能够继续提供该选项。

编辑

很快,我希望能够替换 {{content}}更复杂的东西,比如 <input type="text" /><input type="datetime" />用于编辑时的文本和日期控件。当我想要在内部添加更复杂的标记时,当前的解决方案将不起作用。

最佳答案

已更新

在指令中使用嵌入为您提供了操作 DOM 的选项,可以访问编译/链接函数中嵌入的内容。在那里,您可以使用 jqLit​​e 用 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

关于javascript - 简单的 AngularJS 替换指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23638321/

相关文章:

javascript - jquery footable $ ('#classes' ).trigger ('footable_redraw' );返回隐藏表

JavaScript 中的 PHP 值

javascript - 更改要打印的字体系列和字体大小

javascript - 如何自动分页取决于angularjs中的容器高度

javascript - Angular JS 中的绑定(bind)问题(嵌套变量)

javascript - jquery在一段时间后淡入屏幕

javascript - AngularJS slider 自定义值

angularjs - OnsenUi Angular 和登录

javascript - 从另一个模块访问范围的指令

javascript - 通过 Angular Directive(指令)删除然后添加元素会破坏输入 [radio] 上的 ng-model