directive共用 及 定义公共controller或者 service 多个页面调用

本文探讨了如何在Angular中实现directive的跨页面复用。通过理解module的结构,可以将directive定义在一个公共模块中,并在多个页面中引入该模块以实现复用。示例代码展示了如何创建和引入公共的controller、service和factory。
摘要由CSDN通过智能技术生成

一直都听说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" };
}]);

像上面这样就可以了。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值