简体   繁体   English

角度-通用指令

[英]Angular - General Purpose Directives

I created a generic directive which I'd like to use in any Angular page in our site. 我创建了一个通用directive ,希望在我们网站的任何Angular页面中使用。 I don't want to force each page to use the same app variable. 我不想强迫每个页面使用相同的app变量。 How would I change this directive to be generic so that it could be just added as a dependency (included as a separate js file of course)? 我将如何将该指令更改为通用指令,以便可以将其作为依赖项添加(当然也包括在单独的js文件中)?

var app = angular.module('myapp', []);

app.directive('helloWorld', function() {
 return {
  restrict: 'AE',
  replace: 'true',
  scope: {
  name: '@',
 },
 template: '<h3 >Hello {{name}}</h3> ',

   }
  };
});

You can create a common module, declare your directive on it and use it as a module dependency on each of your apps. 您可以创建一个common模块,在其上声明指令,并将其用作每个应用程序上的模块依赖项。 By adding the module on your app module dependencies you'll be able to use your directive and also every provider your've declared on your common module. 通过在应用程序模块依赖项上添加模块,您将能够使用指令以及在common模块上声明的每个提供程序。

/common.module.js

;(function() {

    var commom = angular.module('common', []);

    commom.directive('helloWorld', function() {
        return {
            restrict: 'AE',
            replace: true,
            scope: {
                name: '@',
            },
            template: '<h3 >Hello {{name}}</h3> ',
        };
    });

})();

/index.html

<html>
...
<body ng-app="myapp">

    <hello-world name="World"></hello-world>

    <script src="angular.min.js"></script>
    <script src="common.js"></script>
    <script>    
        var app = angular.module('myapp', ['common']);
    </script>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM