我创建了一个 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 的选项,可以访问编译/链接函数中嵌入的内容。在那里,您可以使用 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>
关于javascript - 简单的 AngularJS 替换指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23638321/