Skip to content

Instantly share code, notes, and snippets.

@mritzco
Created February 19, 2014 06:03
Show Gist options
  • Save mritzco/9086818 to your computer and use it in GitHub Desktop.
Save mritzco/9086818 to your computer and use it in GitHub Desktop.
Angularjs different directives sharing state (revised)

Angularjs different directives sharing state (revised)

Using inheritance for directives to access the parent controller.

Notice that it's also possible to implement this with a parent directive implementing the controller.

This example is similar to other I posted before but removes the use of $parent

See in plunkr

http://plnkr.co/edit/B16sbZ?p=preview

See the gist code

https://gist.github.com/mritzco/9086818

var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.active = 0;
$scope.setActive = function(id) {
$scope.active = id;
}
$scope.isActive = function(id) {
return (id == $scope.active);
}
});
app.directive('stateful', function() {
return {
restrict: 'AE',
require: '^MainCtrl',
template: "<div ng-class='{active: isActive(id)}'>{{name}}-{{id}} <button ng-click='setActive(id)'>click</button></div>",
replace: true,
scope : { id:"@stateful", name:"@" }
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="http://code.angularjs.org/1.2.12/angular.js" data-semver="1.2.12"></script>
<script src="app.js"></script>
</head>
<body ng-app="myApp" ng-controller="MainCtrl">
<h3>Some controls sharing state through the parent <small>Revised to stop using $parent</small></h3>
<div>
<div stateful="1" name="a"></div>
<div stateful="2" name="b"></div>
<div stateful="3" name="c"></div>
<div stateful="4" name="d"></div>
<div stateful="5" name="e"></div>
</div>
<a href="http://plnkr.co/edit/B16sbZ?p=preview">See in plunkr</a>
</body>
</html>
body {
font-family: Arial;
font-size:12px;
}
.active {
background:red;
}
.hidden {
opacity: .3;
}
div {
display:block;
float: left;
margin:10px 15px;
border: 1px solid #ccc;
padding:5px;
}
h4 {
display:block;
float:none;
clear:both;
font-size:10px;
color:#555;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment