Created
March 22, 2014 15:27
-
-
Save wengzilla/9708975 to your computer and use it in GitHub Desktop.
Templating AngularJS App
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
<html ng-app="TemplateApp"> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> | |
</head> | |
<body> | |
<div ng-controller="TemplateController"> | |
<h1>Input</h1> | |
<div id="templateInputs"> | |
</div> | |
<h1>Template</h1> | |
<textarea ng-model="template"> | |
</textarea> | |
<h1>Output</h1> | |
<div compile="template | breakFilter"></div> | |
</div> | |
<script> | |
var app = angular.module("TemplateApp", []); | |
app.controller("TemplateController", ["$scope", "$compile", function($scope, $compile) { | |
$scope.$watch("template", function(template) { | |
if (template != undefined) { | |
matches = getMatches(template, /{{([^{]*)}}/g, 1); | |
if (matches != undefined) { | |
$('#templateInputs').html(""); | |
for(i = 0; i < matches.length; i++) { | |
$('#templateInputs').append('<input type="text" ng-model="' + matches[i] + '" placeholder=' + matches[i] + '>'); | |
} | |
$compile($('#templateInputs').contents())($scope); | |
} | |
} | |
}); | |
getMatches = function(string, regex, index) { | |
index || (index = 1); // default to the first capturing group | |
var matches = []; | |
var match; | |
while (match = regex.exec(string)) { | |
matches.push(match[index]); | |
} | |
return matches; | |
} | |
}]); | |
app.directive('compile', ['$compile', function ($compile) { | |
return function(scope, element, attrs) { | |
scope.$watch( | |
function(scope) { | |
// watch the 'compile' expression for changes | |
return scope.$eval(attrs.compile); | |
}, | |
function(value) { | |
// when the 'compile' expression changes | |
// assign it into the current DOM | |
element.html(value); | |
// compile the new DOM and link it to the current | |
// scope. | |
// NOTE: we only compile .childNodes so that | |
// we don't get into infinite loop compiling ourselves | |
$compile(element.contents())(scope); | |
} | |
); | |
}; | |
}]); | |
app.filter('breakFilter', function () { | |
return function (text) { | |
if (text !== undefined) return text.replace(/\n/g, '<br />'); | |
}; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment