1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| //指令中监听数据的变化、数据变化的传播
<body ng-app="ezstuff" ng-init="sb = {name:'somebody',gender:'male',age:28}"> <ez-namecard-editor data="sb"></ez-namecard-editor> <div ez-logger data="sb"></div> </body> angular.module("ezstuff", []) .directive("ezNamecardEditor", function () { return { restrict: "E", template: "<ul class='nceditor'></ul>", replace: true, link: function (scope, element, attrs) { //获得变量名称 var model = attrs.data; //展开HTML模板,使用field属性标记对应字段 element.append("<li>name : <input type='text' field='name'></li>") .append("<li>gender : <input type='text' field='gender'></li>") .append("<li>age : <input type='text' field='age'></li>");
//监听DOM事件,变化时修改变量值 element.find("input").on("keyup", function (ev) { var field = ev.target.getAttribute("field"); scope[model][field] = ev.target.value; //将对scope的修改进行传播 scope.$apply(""); }); } }; }) .directive("ezLogger", function () { return { restrict: "A", link: function (scope, element, attrs) { var model = attrs.data; //获得变量名称 scope.$watch(model, function (nv) { var cnt = JSON.stringify(nv, null, " "); //stringify的用法 element.html("<pre>" + cnt + "</pre "); }, true); } }; });
|