directive共用 及 定義公共controller或者 service 多個頁面呼叫
阿新 • • 發佈:2019-02-11
一直都聽說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" };
}]);
像上面這樣就可以了。