2015-03-19 46 views
2

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

你必须弄清楚什么事件触发的变化,并调用'$ scope.apply()'。在这种情况下,手表可能是多余的。例如:'element.on('input',function(){$ scope。$ apply(function(){...});})'。 – 2015-03-19 12:45:05

回答

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

    }); 



    } 


    }; 


});