Override angular components

overriding angular components decorator

by Mohan Rathour

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="demo">
	<h1>Overriding components definitions in AngularJS</h1>
	<selector></selector>
</div>

JavaScript

// Create an application module for our demo.
angular.module("demo", []);

// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
// *** NOTE: We are defining the first module with one component ***

class Ctrl1 {
	constructor() {
		this.description = "I'm the FIRST component";
	}
}

let Component1 = {
	controller: Ctrl1,
	template: "<div style='background-color: green;color: white;'>{{ $ctrl.description }}</div>"
};

let mod1 = angular.module("mod1", [])
	.component("selector", Component1)
	.name;

// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
// *** NOTE: We are defining the second module with one component on the same selector ***

class Ctrl2 extends Ctrl1 {
	constructor() {
		super();
		this.description = "I'm the SECOND component";
	}
}

let Component2 = {
	controller: Ctrl2,
	template: "<div style='background-color: red;color: white;'>{{ $ctrl.description }}</div>"
};

let mod2 = angular.module("mod2", [])
	.component("selector", Component2)
	.decorator("selectorDirective", ($delegate) => {

		// CAUTION: Because I am using the .decorator() module method, this call has
		// to come AFTER the value that it is decorating. This is different than the
		// .config() block, which can be invoked at any point in the module definition.
		// --

		console.log(". . . . . . . . . . . . . . . . .");
		console.log("There are %s matching components ", $delegate.length);
		console.log("Selecting the latest one.");
		console.log(". . . . . . . . . . . . . . . . .");

		let index = $delegate.length - 1;
		let returnComponent = $delegate[index];

		// Return a new array that contains only the latest-selected version
		// of the component.
		return [returnComponent];
	})
	.name;


//...