Last active
June 13, 2020 02:13
-
-
Save rcline/bc230ffbc2feae6829faaa5717a07f7c to your computer and use it in GitHub Desktop.
Render templates or DOM elements inside a Svelte component with AngularJS
This file contains hidden or 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
/** | |
* svelte2Angularjs | |
* | |
* Render templates or DOM elements inside a Svelte component with AngularJS | |
* | |
* Usage: | |
* svelte2Angularjs({ el: ngDom }); | |
* svelte2Angularjs({ | |
* el: ngDom2, | |
* template: `<span> {{mode === 'recent' ? 'Recent Activity' : 'Feed'}}</span>`, | |
* vars: { mode: mode } | |
* }); | |
* | |
* Tip: | |
* Use Svelte's `bind:this`: | |
* <span bind:this={ngDom2} /> | |
* | |
* @param el | |
* @param template | |
* @param vars | |
* @param useElementScope | |
* @param useParentScope | |
*/ | |
export default function svelte2Angularjs({ | |
el, // HTMLElement to compile or replace (if template is passed) | |
template, // String to append to the DOM. Must render to a single node, can't be a document fragment. | |
vars, // Augmentations to scope for use in the template | |
useElementScope = false, // Remove Isolated scope and use the inherited scope of the last AngularJS element | |
useParentScope = false, // Remove Isolated scope and use the AngularJS root scope | |
}) { | |
if (!el) { | |
throw Error('svelte2Angularjs: el param required'); | |
} | |
if ((useElementScope || useParentScope) && !vars) { | |
throw Error('svelte2Angularjs: You must have isolated scope to pass in template variables'); | |
} | |
// Create an injector associated with our `Crops` app on document.body | |
const injector = angular.element(document.body).injector(); | |
injector.invoke(function($rootScope, $compile) { | |
let scope; | |
if (useParentScope) { | |
// Use AngularJS app root scope | |
scope = $rootScope; | |
} else if (useElementScope) { | |
// Inherit the scope of the last AngularJS element | |
scope = angular.element(el).scope(); | |
} else { | |
// Default to isolated scope | |
scope = $rootScope.$new(true); | |
Object.assign(scope, vars); | |
} | |
if (!!template) { | |
const compiledTemplate = $compile(template)(scope)[0]; | |
el.replaceWith(compiledTemplate); | |
} else { | |
$compile(el)(scope); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment