Javascript 基于状态动态添加/删除属性指令
我想构建一个指令,根据布尔标志添加和删除第二个指令 因此,当boolFlag=true时,example.html中的div应该重新编译,以包含my dir作为属性。并且它应该具有我的dir所需的附加属性,格式为“test=1” 以下是到目前为止我所掌握的基本知识: example.html----Javascript 基于状态动态添加/删除属性指令,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我想构建一个指令,根据布尔标志添加和删除第二个指令 因此,当boolFlag=true时,example.html中的div应该重新编译,以包含my dir作为属性。并且它应该具有我的dir所需的附加属性,格式为“test=1” 以下是到目前为止我所掌握的基本知识: example.html---- add-remove-directive.js---- 函数($compile,$timeout){ 返回{ 限制:“A”, 链接:功能(范围、要素、属性){ var attrray=attrs
add-remove-directive.js----
函数($compile,$timeout){
返回{
限制:“A”,
链接:功能(范围、要素、属性){
var attrray=attrs.dirAttrs.split(',');
for(数组中的a){
attrArray[a]=attrArray[a].trim();
}
属性$observe('when',function(){
//当指令应附加到元素时标记
var isWhen=attrs.when=='true';
如果(isWhen){
对于(a=0;a
---编辑---
对不起,这是我从我的项目中复制过来的一个错误。它的功能取决于我在原始帖子中所描述的
基本上现在的情况是,我可以使用相应的必需属性“test=1”动态地正确地执行“mydir”指令
但我遇到的问题是:
- 有两个作用域处于活动状态—原始作用域没有“my dir”,另一个作用域有“my dir”
- 当boolFlag设置为false时,我的else语句不能正确地从div中删除“my dir”
return
部分不是有效的javascript。你确定你的代码就是这样设置和部分工作的吗?演示也有助于更好地了解情况。我添加了从项目复制代码时遗漏的其余角度指令头return
部分不是有效的javascript。你确定吗这就是你的代码是如何设置和部分工作的?一个演示还可以帮助你更好地了解正在发生的事情。我已经添加了我在复制我的项目中的代码时遗漏的其他角度指令头
<div add-remove when={{boolFlag}} dir-name="my-dir" dir-attrs="test, 1"></div>
function($compile, $timeout) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var attrArray = attrs.dirAttrs.split(',');
for (a in attrArray) {
attrArray[a] = attrArray[a].trim();
}
attrs.$observe('when', function() {
// flagged when the directive should be attached to the element
var isWhen = attrs.when === 'true';
if (isWhen) {
for (a = 0; a < attrArray.length; a+=2) {
elem.attr(attrArray[a], attrArray[a+1]);
}
newScope = scope.$new();
cElem = $compile(elem)(newScope);
elem.replaceWith(cElem);
$timeout(function() {
scope.$destroy();
});
}
// if the flag is not set, remove the dynamic directive from the element
// but only if the element already has the given directive
else {
normDirName = attrs.$normalize(attrs.dirName);
console.log(normDirName);
console.log(r, 'elsed', attrs);
if (!attrs.hasOwnProperty(normDirName)) return;
elem.removeAttr(scope.dirName);
for (a = 0; a < attrArray.length; a+=2) {
elem.removeAttr(attrArray[a]);
}
newScope = scope.$new();
cElem = $compile(elem)(newScope);
elem.replaceWith(cElem);
$timeout(function() {
scope.$destroy();
});
}
}
}