Last active
August 29, 2015 14:15
-
-
Save statico/f4d8c106862e333ee2e3 to your computer and use it in GitHub Desktop.
angular-directive-reloading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>angular test</title> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.js"></script> | |
</head> | |
<body> | |
<h3>demo of reloading/replacing angularjs directives</h3> | |
<div id="content" ng-app="myapp"> | |
<div my-thing value="42"></div> | |
</div> | |
<script> | |
// nothing new here -- create a directive. | |
// (default priority is 0) | |
angular | |
.module('myapp', []) | |
.directive('myThing', function() { | |
return { | |
restrict: 'A', | |
scope: { value: '=' }, | |
template: '<div>Thing! value={{ value }}</div>' | |
} | |
}); | |
// now override the directive by doing two things: | |
// 1. create a directive with a higher priority that is terminal: true | |
// 2. create a directive with an even higher priority with the replacement. | |
// two directives are needed because the terminal directive does _nothing_ (no link) | |
// and even the highest-level directive doesn't render templates automatically so we | |
// need to render the template ourselves. | |
angular | |
.module('myapp') | |
.directive('myThing', function($compile) { | |
return { | |
priority: 10, | |
terminal: true | |
} | |
}); | |
angular | |
.module('myapp') | |
.directive('myThing', function($compile) { | |
return { | |
priority: 20, | |
restrict: 'A', | |
scope: { value: '=' }, | |
link: function(scope, el, attrs) { | |
el.html('<div>Thing 2! value={{ value }}</div>'); | |
$compile(el.contents())(scope); | |
}, | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment