一直都听说Angular中的directive自定义指令可以复用,但是给我的感觉很茫然,我知道在同一个页面里面可以复用,但是多个页面之间如何复用呢?
刚一开始我想的是directive是依托在一个module上的,一个页面只能由一个module,即下面的样子:
angular.module("myApp",[]).directive("hello",function()
{
return {
....
}});
我一直使用像上面这样的链式写法,所以要用在多个页面上,就有点茫然了,不知道应该怎么弄,今天才了解到,其中的module的第二个数组参数可以引入其他的module,具体用法,eg:(directive.js)
var helloDirective = angular.module("hello", []);
helloDirective.directive("hello", function () {
return {
restrict: 'E',
template: "<div style='border:1px dotted red;'>789 <span ng-transclude><span></div>",
replace: true,
transclude: true,
}
});
页面html,like this:
<script src="../Scripts/angular.min.js"></script>
<script src="directive.js"></script>
<script>
angular.module("myApp", ["hello"]);
</script>
</head>
<body ng-controller="myController">
<hello>123456</hello><br />
</body>
同理,我们可以在这里注入公用的controller、service、factory等。如果需要引入多个module的话,要用逗号隔开,like this:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../Scripts/angular.min.js"></script>
<script src="directive.js"></script>
<script>
angular.module("myApp", ["hello", "myCtrl"]);
</script>
</head>
<body ng-controller="myController">
<hello>123456</hello><br />
{{person.name}}
</body>
js like this:
var helloDirective = angular.module("hello", []);
helloDirective.directive("hello", function () {
return {
restrict: 'E',
template: "<div style='border:1px dotted red;'>789 <span ng-transclude><span></div>",
replace: true,
transclude: true,
}
});
var myController = angular.module("myCtrl", []);
myController.controller("myController", ["$scope", function ($scope) {
$scope.person = { name: "wenbin" };
}]);
像上面这样就可以了。