Angularjs 指令复制其中的元素
Angularjs directive duplicates the elements inside it
(function () {
'use strict';
angular.module('product')
.directive('sampledirective', ['$document') {
return {
restrict: 'E',
replace: true,
scope: {
data: '=',
btnClick: '&'
},
link: function (scope, element, attr) {
var compiled = $compile(template)(scope);
angular.element(element).replaceWith(compiled);
element = compiled;
};
};
}]);
})();
我有一个指令可以替换其中的元素。
我有一个奇怪的问题,它多次替换指令中的元素。
复制下面粗体行中不应发生的元素。
angular.element(element).replaceWith(compiled);
请告诉我为什么元素重复,并让我知道如何避免它。
样本
实际
cool cool
预计
cool
以下指令在我的例子中只替换了一次内容。如果这不能解决您的问题,也许您可以提供一个小的工作示例。另请注意,如果您为指令使用独立范围,则应提供模板,如 this post.
中所述
angular.module('product').directive("sampledirective", function ($compile) {
return {
template: '',
restrict: 'E',
scope: {
data: "=data",
btnClick: '&'
},
link: function (scope, element, attrs) {
var template = "<div>foo</div>"
var compiled = $compile(template)(scope);
element.replaceWith(compiled);
}
}
});
(function () {
'use strict';
angular.module('product')
.directive('sampledirective', ['$document') {
return {
restrict: 'E',
replace: true,
scope: {
data: '=',
btnClick: '&'
},
link: function (scope, element, attr) {
var compiled = $compile(template)(scope);
angular.element(element).replaceWith(compiled);
element = compiled;
};
};
}]);
})();
我有一个指令可以替换其中的元素。 我有一个奇怪的问题,它多次替换指令中的元素。
复制下面粗体行中不应发生的元素。
angular.element(element).replaceWith(compiled);
请告诉我为什么元素重复,并让我知道如何避免它。
样本
实际
cool cool
预计
cool
以下指令在我的例子中只替换了一次内容。如果这不能解决您的问题,也许您可以提供一个小的工作示例。另请注意,如果您为指令使用独立范围,则应提供模板,如 this post.
中所述angular.module('product').directive("sampledirective", function ($compile) {
return {
template: '',
restrict: 'E',
scope: {
data: "=data",
btnClick: '&'
},
link: function (scope, element, attrs) {
var template = "<div>foo</div>"
var compiled = $compile(template)(scope);
element.replaceWith(compiled);
}
}
});