AngulatJS $directive compile
<!DOCTYPE html> <html> <head> <title></title> <script src="angular.min.js"type="text/javascript"></script> </head> <body ng-app="demo"> <dump-Password></dump-Password> </body> <script> var demo = angular.module("demo",[]); demo.directive("dumpPassword",function(){ var el = angular.element("<pre>{{model.input}}</pre>"); return { restrict:"E", replace:true, template:"<div><input type='text' ng-model='model.input'></div>", compile:function(element){ element.append(el); return function(scope,element){ scope.$watch("model.input",function(value){ if(value==="password"){ el.addClass("Jackey"); console.log("ok"); } }); } } }; }); </script> </html>
compile和link的功能差不多,一般在compile里面做一些初始化的工作,有conpile的时候,就不要写link了,把link的功能在compile里面return回来。个人观点。