Skip to content

Instantly share code, notes, and snippets.

@Sija
Last active October 8, 2018 23:34
Show Gist options
  • Save Sija/d502a320a602ae07386cf010f04e2b0e to your computer and use it in GitHub Desktop.
Save Sija/d502a320a602ae07386cf010f04e2b0e to your computer and use it in GitHub Desktop.
Typeform embed module for AngularJS 1.x
'use strict'
###*
# @ngdoc overview
# @name angularTypeform
# @description
# This module contains a directive that allows you easily embed a typeform
# in your angular 1.x app taking care about state changes
###
angular.module 'angularTypeform', []
.provider 'typeformConfig', ->
@accountId = ''
@setAccount = (value) ->
@accountId = value
return
@$get = -> this
return
.controller 'ControllerEmbed', ($scope, $element, typeformConfig, $timeout) ->
if typeformConfig.accountId
$scope.accountId = typeformConfig.accountId
else
throw new EvalError 'Typeform account ID not set in config'
initTypeformScript = ->
d = document
gi = d.getElementById
ce = d.createElement
gt = d.getElementsByTagName
id = 'typef_orm'
b = 'https://embed.typeform.com/'
unless gi.call(d, id)
js = ce.call(d, 'script')
js.id = id
js.src = b + 'embed.js'
q = gt.call(d, 'script')[0]
q.parentNode.insertBefore js, q
else
# For angular apps
new window.typeformEmbed.makeWidget($element[0], $scope.formUrl)
return
$timeout ->
initTypeformScript()
return
return
.directive 'typeformEmbed', ($sce, $httpParamSerializer) ->
restrict: 'EA'
replace: yes
scope:
tfId: '@'
tfText: '@?'
tfStyle: '@?'
tfHidden: '=?'
template: '
<div class="typeform-widget" \
ng-attr-data-url="{{formUrl}}" \
ng-attr-data-text="{{tfText}}" \
ng-attr-style="{{tfStyle}}">\
</div>'
controller: 'ControllerEmbed'
link: (scope, element, attrs) ->
scope.urlParams = $httpParamSerializer scope.tfHidden
attrs.$observe 'tfId', ->
formUrl = "https://#{scope.accountId}.typeform.com/to/#{scope.tfId}"
formUrl += "?#{scope.urlParams}" if scope.urlParams
scope.formUrl = $sce.trustAsResourceUrl formUrl
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment