Skip to content

Instantly share code, notes, and snippets.

@thekarel
Created October 19, 2013 23:37
Show Gist options
  • Save thekarel/7062911 to your computer and use it in GitHub Desktop.
Save thekarel/7062911 to your computer and use it in GitHub Desktop.
Create scope variable from the original HTML of a directive in AngularJS
var myApp = angular.module('myApp', []);
myApp.directive('collapsible', function () {
/**
* We need this since by the time we get to link,
* the original HTML is already gone, replaced by template.
*/
var originalHTML = {};
return {
restrict: 'E',
transclude: false,
scope: {},
link: function(scope, element) {
scope.open = false;
scope.toggle = function(what) {
scope[what] = !scope[what];
};
scope.title = originalHTML.h1;
},
template: function(element, attrs) {
var div = element.find('div').html();
originalHTML.h1 = element.find('h1').html();
var html = ''+
'<div>'+
'<h1 ng-click="toggle(\'open\')">{{title}}</h1>'+
'<div ng-show="open">'+
div+
'<hr> Edit the title: <input type="text" ng-model="title">'+
'</div>'+
'</div>';
return html;
}
};
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>The Application</title>
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angular/angular-route.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<collapsible>
<h1>HPMOR</h1>
<div>Harry Potter and the Methods of Rationality</div>
</collapsible>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment