angular decorator - archering/basic GitHub Wiki

Every directive is a special service inside AngularJS, you can override or modify any service in AngularJS

在AngularJS中,我们可以使用Angular内置或者自定义的services,在应用的各个部分之间分享数据和方法。假设你已经定义了一个service,但是在使用了一段时间之后又想要为这个service添加一些功能怎么办? 方法之一当然是修改这个service的定义,直接在源码上动刀子。但是现在很多项目都需要通过团队协作来完成,直接修改别人的代码可能需要花费不少功夫,同时还要防范“牵一发而动全身”的风险。更进一步,如果你想给一些Angular内置的service添加功能怎么办,难道要我直接阅读angular.js的源码么?

方法二,Angular为我们提供了一种非常简单而优雅的方式来为service添加功能,它就是Angular中的decorator。

##实例


<body ng-app="Demo">
	<div me>This is a directive </div>
	<script type="text/javascript" src="../node_modules/angular/angular.min.js"></script>
	<script type="text/javascript">
		var mod = angular.module( "Demo", [] );
		mod
			.directive("me",function sectionDirective() {
					return {
						link: function( scope, element, attributes ) {
							element.html("First directive linked.");
							console.log( "First directive linked." );
						},
						bensLabel: "First-by-Ben"
					};
				}
			)
			.directive("me",function sectionDirective() {
					return {
						link: function( scope, element, attributes ) {
							element.html("2Second directive linked.");
							console.log( "2Second directive linked." );
						},
						bensLabel: "Second-by-Ben"
					};
				}
			)
			.directive("me",function sectionDirective() {
					return {
						link: function( scope, element, attributes ) {
							element.html("3Third directive linked.");
							console.log( "3Third directive linked." );
						},
						bensLabel: "Third-by-Ben"
					};

				}
			);
		mod.decorator("meDirective",function ( $delegate ) {
				var randomIndex = Math.floor( Math.random() * $delegate.length );
				var randomDirective = $delegate[ randomIndex ];
				return  [ randomDirective ];				
			}
		);
	</script>
</body>
</html>
</code>

或者这种


	module.directive("sisi", [function () {
		return {
			compile:function(element,attrs){
				element.html("this is not me")
				return this.link;
			},
			link:function(scope,element){
				scope.clickme = function(){
					alert(123);
				}
			}
		}
		
		
	}]);

	
	module.decorator("sisiDirective",function($delegate){
		var newsisi = $delegate[0];
		newsisi.compile = function(element,attrs){
			element.html("this is  me");
			return this.link;
		};
		newsisi.link = function(scope){
			scope.clickme2 = function(){
				alert(321);
			}
		}
		return [newsisi];
	});

⚠️ **GitHub.com Fallback** ⚠️