import ngModule from '../module'; export function stringifyParams(data) { const params = Object.assign({}, data.params); for (let param in params) params[param] = JSON.stringify(params[param]); return params; } export function changeState($state, event, data) { const params = stringifyParams(data); $state.go(data.state, params); event.preventDefault(); event.stopPropagation(); } export function openNewTab($state, $window, event, data) { const params = stringifyParams(data); const href = $state.href(data.state, params); $window.open(href); event.preventDefault(); event.stopPropagation(); } /** * Allows changing state for nested anchor * * @param {Object} $state * @param {Object} $window * @return {Object} The directive */ export function directive($state, $window) { let ctrlPressed = false; $window.addEventListener('keydown', event => { if (event.key == 'Control') ctrlPressed = true; }); $window.addEventListener('keyup', event => { if (event.key == 'Control') ctrlPressed = false; }); return { restrict: 'A', link: function($scope, $element, $attrs) { const data = $scope.$eval($attrs.vnAnchor); $element.on('click', event => { if (ctrlPressed || data.target == '_blank') openNewTab($state, $window, event, data); else changeState($state, event, data); }); $element.on('mousedown', event => { const mouseWheel = 1; if (event.button == mouseWheel) openNewTab($state, $window, event, data); }); } }; } directive.$inject = ['$state', '$window']; ngModule.directive('vnAnchor', directive);