Javascript 使用$watch更改html内容

Javascript 使用$watch更改html内容,javascript,angularjs,watch,Javascript,Angularjs,Watch,如何使用$watch更改div的html内容。我尝试了使用示例,但它不起作用。它是第一次手表,每当有变化时,手表不会被触发。请在下面查找代码 html 棱角的 var myApp = angular.module('myApp',[]); myApp.directive('editableContent', function(){ return { replace: true, template:'<div contentEditable style="border:1px so

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

html


棱角的

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);

    });



  }


  };


});
var myApp=angular.module('myApp',[]);
myApp.directive('editableContent',function(){
返回{
替换:正确,
模板:'这是
一分为二,,
链接:功能(范围、元素、属性){
范围$watch(函数()
{return element.html()},函数(值){
console.log(值);
});
}
};
});

我建议您应该在指令中使用独立作用域,为内容设置一个变量,并且您可以轻松地观察该变量的变化

html


js

var myApp=angular.module('myApp',[]);
myApp.directive('editableContent',function(){
返回{
替换:正确,
范围:{
内容:'='
}
模板:'这是
一分为二,,
链接:功能(范围、元素、属性){
范围$watch(函数()
{scope.content},函数(值){
console.log(值);
});
}
};
});

您必须找出触发更改的事件,并调用
$scope.apply()
。在这种情况下,手表可能是多余的。类似于:
element.on('input',function(){$scope.$apply(function(){…});})
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);

    });



  }


  };


});
<body ng-app="myApp">
   <div editable-content></div>
  </body>
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);

    });



  }


  };


});