我们通常会期望通过复杂的DOM结构替换掉directive(所在的元素?目的大概是使directive内部复杂点,看起来牛点@_@)。这让directive成为使用可复用组件的建立应用的一个快捷方式。
下面是一个可复用组件的例子:
<!DOCTYPE html> <html ng-app="ZippyModule"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>ZippyModule</title> <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"> <style type="text/css"> .zippy { border: 1px solid black; display: inline-block; width: 250px; } .zippy.opened > .title:before { content: '▼ '; } .zippy.opened > .body { display: block; } .zippy.closed > .title:before { content: '► '; } .zippy.closed > .body { display: none; } .zippy > .title { background-color: black; color: white; padding: .1em .3em; cursor: pointer; } .zippy > .body { padding: .1em .3em; } </style> <script src="https://www.jb51.net/angular.js" type="text/javascript"></script> </head> <body> <div ng-controller="MyCtrl"> Title: <input ng-model="title" type="text"><br/> Text: <textarea ng-model="text" ></textarea> <hr/> <div zippy-title="Details: {{title}}...">{{text}}</div> </div> <script type="text/javascript"> var myModule = angular.module("ZippyModule", []); myModule.controller("MyCtrl", function ($scope) { $scope.title = "这里是标题"; $scope.text = "这里是内容哇。。。"; }); myModule.directive('zippy', function () { return { template: '<div>' + ' <div>{{title}}</div>' +//这个title属于当前directive isolate scope的property ' <div ng-transclude></div>' + //这里的东西,获取的是父scope的property咯 '</div>', replace:true, transclude: true, restrict:'C', scope:{ title:"@zippyTitle"//绑定directive元素身上的zippy-title属性 }, link:function(scope,element,attrs) { var title = angular.element(element.children()[0]), opened = false; title.bind("click", toogle); element.addClass("closed"); function toogle() { opened = !opened; element.removeClass(opened ? "closed" : "opened"); element.addClass(opened ? "opened" : "closed"); } } }; }); </script> </body> </html>
您可能感兴趣的文章: