使用$ watch更改html内容

时间:2015-03-19 12:40:36

标签: javascript angularjs watch

如何使用$ 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);

    });



  }


  };


});

1 个答案:

答案 0 :(得分:1)

我建议您在指令中使用隔离范围,为内容添加变量,并且您可以轻松地观察此变量。

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

    });



  }


  };


});