你的位置:首页 > Java教程

[Java教程]在Angularjs中使用directive自定义指令实现attribute的继承

一、Html代码:

 1 <!DOCTYPE html> 2 <html ="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) { });

 

效果如下所示: