restrict : E/A/C/M 绑定元素的类型 E element A attribute C class M comment
template: 返回的string
replace :是否去掉外层wrap
controller 内置的控制器
简单例子:
<!DOCTYPE html> <html ng-app="demo"> <head> <title></title> <script src="angular.min.js" type="text/javascript"></script> </head> <body> <div my-Directive></div> </body> <script> var demo = angular.module("demo", []); demo.controller("demoController", function ($scope) { }); demo.directive("myDirective", function () { return { restrict: "A", replace: true, controller: function ($scope) { $scope.name = "click me"; }, template: "<a href=‘http://google.com‘>{{name}}</a>" }; }); </script> </html>
directive 与DOM交互的理解可以通过scope来传递
<!DOCTYPE html> <html ng-app="demo"> <head> <title></title> <script src="angular.min.js" type="text/javascript"></script> </head> <body> <div my-Directive my-Url="http://google.com" my-Text="click me"></div> </body> <script> var demo = angular.module("demo", []); demo.controller("demoController", function ($scope) { }); demo.directive("myDirective", function () { return { restrict: "A", replace: true, controller: function ($scope) { //$scope.name = "click meee"; }, scope:{ myUrl:"@", myText:"@" }, template: "<a href=‘{{myUrl}}‘>{{myText}}</a>" }; }); </script> </html>
再看另外一个例子
<!DOCTYPE html> <html ng-app="demo"> <head> <title></title> <script src="angular.min.js" type="text/javascript"></script> </head> <body> <input type="text" ng-model="theirUrl" /> <div my-Directive my-Url="http://google.com" my-Text="click me" some-Attr="theirUrl"></div> </body> <script> var demo = angular.module("demo", []); demo.controller("demoController", function ($scope) { }); demo.directive("myDirective", function () { return { restrict: "A", replace: true, controller: function ($scope) { //$scope.name = "click meee"; }, scope:{ myUrl:"=someAttr",//modified myText:"@" }, template: "<a href=‘{{myUrl}}‘>{{myText}}</a>" }; }); </script> </html>
用theirUrl将some-Attr关联起来,通过scope传递值进去directive