一、Html代碼: 二、tmp.html文件 三、Js代碼: 效果如下所示: ...
一、Html代碼:
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 <script src="../../Content/Plugins/Angular/angular.min.js"></script> 7 </head> 8 <body ng-app="mainApp" ng-controller="mainController"> 9 <quber-grid style="border: 1px solid #f00;" title="qubernet"></quber-grid> 10 </body> 11 </html>
二、tmp.html文件
1 <div quber-grid-attr> 2 我是測試的模板內容! 3 </div>
三、Js代碼:
1 //初始化Angular對象 2 var myNg = angular.module('mainApp', []); 3 4 myNg.directive('quberGrid', function () { 5 return { 6 restrict: 'EA', 7 replace: true,//移除<quber-grid>標簽 8 templateUrl: 'tmp.html', 9 link: function (sco, ele, attr) { 10 //通知下屬DOM,執行名為sendChildGridAttr的事件 11 sco.$broadcast('sendChildGridAttr', attr); 12 } 13 }; 14 }); 15 myNg.directive('quberGridAttr', function () { 16 return { 17 restrict: 'A', 18 link: function (sco, ele, attr) { 19 sco.$on('sendChildGridAttr', function (event, data) { 20 angular.forEach(data, function (val, key, obj) { 21 if (key != '$attr' && key != '$$element') { 22 //設置標簽屬性和值 23 attr.$set(key, val); 24 } 25 }); 26 }); 27 } 28 }; 29 }); 30 31 myNg.controller('mainController', function ($scope) { });
效果如下所示: