Angularjs 通过指令动态更改元素的HTML
我试图根据作为指令属性传递的变量更改元素的HTML 内容应更改回“这是原始内容…”。为什么它不起作用 HTMLAngularjs 通过指令动态更改元素的HTML,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我试图根据作为指令属性传递的变量更改元素的HTML 内容应更改回“这是原始内容…”。为什么它不起作用 HTML 这是原始内容。changingVar是{{testObj.changingVar}} JS var-app=angular.module('myApp',[]); app.controller('myCtrl',函数($scope,$timeout){ $scope.testObj={}; $scope.testObj.changingVar=false; $timeout(函数(
这是原始内容。changingVar是{{testObj.changingVar}}
JS
var-app=angular.module('myApp',[]);
app.controller('myCtrl',函数($scope,$timeout){
$scope.testObj={};
$scope.testObj.changingVar=false;
$timeout(函数(){
log(“超时完成了!现在应该恢复原始内容(从指令内部的某个地方!)”;
$scope.testObj.changingVar=true;
}, 5000);
});
app.directive('loadingData',function(){
返回{
限制:“AE”,
替换为:“false”,
链接:功能(范围、要素、属性){
var originalHTML=elem[0]。innerHTML;
元素替换为(“这是修改的内容””;
//当testObj.changingVar为true时,我希望设置原始内容(存储在var‘originalHTML’中)!
//怎么办?
// ........................................... ?
// ........................................... ?
}
}
});
第一个答案很有用;很抱歉,我不小心保存了带有一些注释掉的部分的JSFIDLE。现在更新
有一个答案建议使用对象是有用的(通过引用传递)
,而不是只传递一个变量(通过值传递)
——很高兴知道这一点
我再次更新了JSFIDLE,以说明我正在努力做得更好:
您要传递的第一件事
testObj
意味着您不想将继承的作用域与指令一起使用
所以,我假设你想使用
据此,,
这是变化
HTML:
<div test-data='testObj'>
<p> This is the original content. changingVar is '{{testObj.changingVar}}'</p>
</div>
如果您希望根据数据更改更新html,则可以将其置于传递对象的属性中
根据上述假设,您应该使用with指令。
这只不过是使用=
app.directive('loadingData', function() {
return {
restrict: 'AE',
replace: false,
scope : {testData:'=testData'},
link: function(scope, elem, attrs) {
var originalHTML = elem[0].innerHTML;
elem.html("<p>This is modified content</p>");
scope.$watch(function(){
return scope.testData.changingVar;
},function(nVal){
console.log('1')
elem.html("<p>Here is the original content</p>");
})
}
}
});
app.directive('loadingData',function(){
返回{
限制:“AE”,
替换:false,
作用域:{testData:'=testData'},
链接:功能(范围、要素、属性){
var originalHTML=elem[0]。innerHTML;
html(“这是修改过的内容””;
范围$watch(函数(){
返回scope.testData.changingVar;
},功能(nVal){
console.log('1')
html(“这里是原始内容””;
})
}
}
});
这是更新的检查更新的答案
<div test-data='testObj'>
<p> This is the original content. changingVar is '{{testObj.changingVar}}'</p>
</div>
1. replace : false; // implicitly it is false and not 'false';
2. You should not replace directive with html until unless you dont want to refer it again.
app.directive('loadingData', function() {
return {
restrict: 'AE',
replace: false,
scope : {testData:'=testData'},
link: function(scope, elem, attrs) {
var originalHTML = elem[0].innerHTML;
elem.html("<p>This is modified content</p>");
scope.$watch(function(){
return scope.testData.changingVar;
},function(nVal){
console.log('1')
elem.html("<p>Here is the original content</p>");
})
}
}
});