使用$watch更改html内容

using $watch for change in html content

本文关键字:html 内容 更改 watch 使用      更新时间:2023-09-26

如何使用$watch更改div的html内容。我尝试过使用示例,但它不起作用。它是第一次手表,只要有变化,手表就不会被触发。请在下面找到代码

html

<body ng-app="myApp">
   <div editable-content></div>
  </body>

角度

var myApp = angular.module('myApp',[]);
myApp.directive('editableContent', function(){
return {
 replace: true,
 template:'<div contentEditable style="border:1px solid;width:300px;height:40px">this is 
 a div</div>',
 link: function(scope, element, attr){
  scope.$watch(function()
    {return element.html()}, function(value){
    console.log(value);
    });

  }

  };

});

我建议您应该在指令中使用独立的范围,为内容设置一个变量,并且您可以很容易地观察到这个变量的变化。

html

<body ng-app="myApp">
   <div editable-content></div>
  </body>

js

var myApp = angular.module('myApp',[]);
myApp.directive('editableContent', function(){
return {
 replace: true,
 scope:{
      content: '='
 }
 template:'<div contentEditable content='content' style="border:1px solid;width:300px;height:40px">this is 
 a div</div>',
 link: function(scope, element, attr){
  scope.$watch(function()
    {scope.content}, function(value){
    console.log(value);
    });

  }

  };

});