JSFiddle - React, Tailwind, and code Playground
by lottikarotti
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app='app' ng-controller='App'>
<!-- test #1 -->
<compile-component
component='"my-component"'
bindings='{
"twoWay": {"id": 1, "username": "rckd"},
"string": "yo",
"oneWay": $ctrl.user
}'
></compile-component>
<!-- test #2 -->
<compile-component
component='$ctrl.component'
bindings='$ctrl.bindings'
></compile-component>
</div>
JavaScript
console.clear();
var injector = angular.inejctor;
var app = angular.module('app', [])
.controller('App', function($scope){
var ctrl = $scope.$ctrl = {};
ctrl.component = 'myComponent';
ctrl.bindings = {
"twoWay": {"id": 1, "username": "rckd"},
"string": "yo",
"oneWay": {"id": 2, "username": "emil"}
};
ctrl.user = {username: 'affe'};
})
.factory('ngCompileComponentService', [
'$rootScope',
'$compile',
function($rootScope, $compile){
/**
* Transforms "myComponentName" to "my-component-name"
*
* @param {String} string
* @return {String}
*/
function toLowerDash(string){
return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
return{
/**
* Builds the component's html:
*
* <my-component
* two-way='$ctrl["twoWay"]'
* one-way='$ctrl["oneWay"]'
* string='{{ $ctrl["string"] }}'
* ></my-component>
*
* @param {String} component
* @return {Object} bindings
* @return {String}
*/
buildHtml: function(component, bindings){
var tag = toLowerDash(component);
var attrs = '';
var prop = null;
for(prop in bindings){
attrs += ' ' + toLowerDash(prop) + '=\'' + (
typeof bindings[prop] === 'string'
? '{{ $ctrl["' + prop + '"] }}'
: '$ctrl["' + prop + '"]'
) + '\'';
}
return '<' + tag + attrs + '></' + tag + '>';
},
build: function(component, bindings){
var scope = angular.extend($rootScope.$new(), {
$ctrl: bindings
});
var html = this.buildHtml(component, bindings);
return $compile(html)(scope);
}
};
}
])
.directive('compileComponent', [
'ngCompileComponentService',
function(ngCompileComponentService){
return{
restrict: 'E',
scope:{
component: '=',
bindings: '='
},
link: function(scope, element){
var component =...