通过指令动态更改元素的HTML

时间:2016-09-01 17:59:29

标签: angularjs angularjs-directive

我试图根据作为指令属性传递的变量来更改元素的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保存了一些注释掉的部分。现在更新!

有一个答案表明使用对象很有用(passed by reference)而不是传递单个变量(passed by value) - 这很有用。

我再次更新了jsFiddle以说明我想要做得更好:

https://jsfiddle.net/4xbLrg5e/6/

1 个答案:

答案 0 :(得分:0)

您传递的第一件事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.

如果要根据数据更改更新html,可以将watch放到已传递对象的属性中。

您应该按照上述假设使用isolated scope和指令。 这只是passed by reference使用=

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