Last active
April 19, 2016 03:38
-
-
Save chrisjensen/20b86d22661496431168435768232e1f to your computer and use it in GitHub Desktop.
Example of an AngularJS directive that will dynamically change the destination page of a NationBuilder signup form.
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
<div nb-dynamic-page page-id="dynamicPage"> | |
{% form_for signup %} | |
<input ng-model="dynamicPage" type="text" value="122" name="pageId" /> | |
{% submit_tag "Do this action", class:"submit-button" %} | |
{% endform_for %} | |
</div> |
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
angular.module('NBdynamic') | |
.directive('nbDynamicPage', function NBDynamicPageDirective() { | |
return { | |
restrict: 'A', | |
controller: ['$scope', '$element', '$timeout', NBDynamicPageController], | |
scope: { | |
pageId: '=' | |
}, | |
} | |
}) | |
/** | |
* Watches $scope.pageId and updates | |
*/ | |
function NBDynamicPageController($scope, $element, $timeout) { | |
setDestinationPage($scope.pageId); | |
// Update the destination if the action updates | |
$scope.$watch('pageId', function() { | |
setDestinationPage($scope.pageId); | |
}); | |
// Sets the destination page for this action. Only sets it if | |
// action is present | |
function setDestinationPage(page_id) { | |
if (page_id) { | |
// Timeout to give the DOM a chance to render so the | |
// input element can be found | |
$timeout(function() { | |
// Find the hidden form element, update it’s value | |
$element.find("input[name='page_id']").attr('value', page_id); | |
}, 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment