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

标签 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 以及一些注释掉的部分。现已更新!

有一个答案表明使用对象是有用的(通过引用传递)而不是传递单个变量(通过值传递) - 很高兴知道。

<小时/>

我再次更新了 jsFiddle 以说明我试图做得更好:

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

最佳答案

首先,您传递的 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/

相关文章:

javascript - Angular/Bootstrap - 模式不显示(仅背景变化)

javascript - 替代在 url 中使用 hashbangs 来解决 IE9 问题

javascript - 如何在 Controller 中手动注入(inject)路由解析数据?

javascript - 当我使用 angularjs 配置时,页面重定向到 IE8 中的主页

angularjs - 避免太多 Angularjs 指令

javascript - angularjs指令+在许多 Controller 中应用范围值

angularjs - 在 Mongoose 中分组嵌套内部数组

angularjs - 在 Angular 1.4 中通过具有隔离作用域的嵌套指令绑定(bind)函数失败

javascript - Bootstrap 警报消息在 ui-router 下的 Angular 运行 block 内不起作用?

angularjs - 打开时在 AngularUI 模式的输入字段中选择文本