我创建了一个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" />
用于文本和日期控件。当我想要更复杂的标记时,当前的解决方案将不起作用。
答案 0 :(得分:1)
<强>已更新强>
在指令中使用transclusion为您提供了操作DOM的选项,可以访问编译/链接功能中的已转换内容。在那里,您可以使用jqLite用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>
答案 1 :(得分:0)
我创建的Plunker似乎运行正常。
这是你在寻找行为吗?
答案 2 :(得分:0)
我觉得这样的蠢事。见this Plunker。结果我只是想ng-transclude
。