【问题标题】:using $watch for change in html content使用 $watch 更改 html 内容
【发布时间】:2015-03-19 21:36:40
【问题描述】:

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

    });



  }


  };


});

【问题讨论】:

  • 您必须弄清楚是什么事件触发了更改并致电$scope.apply()。在这种情况下,手表可能是多余的。比如:element.on('input', function() { $scope.$apply(function() {...}); }).

标签: javascript angularjs watch


【解决方案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);

    });



  }


  };


});

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 2018-06-19
    • 2013-11-02
    • 2019-06-15
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多