AngularJS Directive to Directive Communication
Egghead.io - 16
by TahmidTanzim
HTML
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css">
<!-- <div ng-controller="myCtrl">
{{test}}
</div>
-->
<!--<super-hero metal fire ice></super-hero>-->
<superhero fire metal>Gag</superhero>
JavaScript
"use strict";
var App = angular.module("myApp", []);
/*
App.controller("myCtrl",["$scope",function($scope){
$scope.test = "Hello";
}]);
*/
App.directive("superhero", function () {
return {
restrict: "E",
scope: {},
controller: function ($scope) {
$scope.powers = [];
this.addFire = function () {
$scope.powers.push("Fire");
};
this.addIce = function () {
$scope.powers.push("Ice");
};
this.addMetal = function () {
$scope.powers.push("Metal");
};
},
link: function (scope, element) {
element.addClass("btn");
element.bind("click", function () {
console.log(scope.powers);
});
}
};
});
App.directive("fire", function () {
return {
require: "superhero",
link: function (scope, element, attrs, superheroCtrl) {
superheroCtrl.addFire();
}
};
});
App.directive("ice", function () {
return {
require: "superhero",
link: function (scope, element, attrs, superHeroCtrl) {
superHeroCtrl.addIce();
}
};
});
App.directive("metal", function () {
return {
require: "superhero",
link: function (scope, element, attrs, superHeroCtrl) {
superHeroCtrl.addMetal();
}
};
});