我正在尝试根据作为指令属性传递的变量来更改元素的 HTML。
内容应该改回“这是原始内容...”。怎么不起作用?
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<div data-loading-data='{{testObj}}'>
<p> This is the original content. changingVar is '{{testObj.changingVar}}'</p>
</div>
</div>
JS
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.testObj = {};
$scope.testObj.changingVar = false;
$timeout(function() {
console.log("time out is done ! the original content should be restored now (from somewhere inside the directive!)");
$scope.testObj.changingVar = true;
}, 5000);
});
app.directive('loadingData', function() {
return {
restrict: 'AE',
replace: 'false',
link: function(scope, elem, attrs) {
var originalHTML = elem[0].innerHTML;
elem.replaceWith("<p>This is modified content</p>");
// When testObj.changingVar will be true, I want the original content (which is stored in var 'originalHTML') to be set!
// How to do?
// ........................................... ?
// ........................................... ?
}
}
});
第一个答案很有用;抱歉,我不小心保存了 jsfiddle 以及一些注释掉的部分。现已更新!
有一个答案表明使用对象是有用的(通过引用传递)
而不是传递单个变量(通过值传递)
- 很高兴知道。
我再次更新了 jsFiddle 以说明我试图做得更好:
最佳答案
首先,您传递的 testObj
意味着您不想将继承的作用域与指令一起使用。
所以,我假设您想使用 isolated scope .
据此, 这是更改,
HTML:
<div test-data='testObj'>
<p> This is the original content. changingVar is '{{testObj.changingVar}}'</p>
</div>
指令 JS: 有一些修正,
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.
您可以输入 watch如果您想根据数据更改更新 html,则传递到传递对象的属性。
您应该使用isolated scope根据上述假设的指令。
这只不过是使用 =
通过引用传递
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>");
})
}
}
});
这是更新后的fiddle
关于angularjs - 通过指令动态更改元素的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39278103/