Angular directives collision - angularjs

I would like to use 2 directives in the same app. The problem is that when I use the second one, the first one crashes with an ugly error: TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
The first directive is angular-fullpage.js (https://github.com/hellsan631/angular-fullpage.js) and the second one is angular bootstrap affix implementation (https://github.com/maxisam/angular-bootstrap-affix).
When I include both modules (directives), the fullpage directive crashes with the afformentioned error. If I remove the affix directive, then fullpage.js Works fine (just by removing the second directive from the modules).
How can I avoid directive collision? Are there any workarounds for this issue or should I just settle for just 1 of the directives?
Thanks!!!!
app.js:
var myApp = angular
.module(
'myApp',
[
'ngRoute',
'ngAnimate',
'ngMessages',
'ui.bootstrap',
'angular-loading-bar',
'LocalStorageModule',
'ngEnter',
'ng-Static-Include',
'ngResource',
'toastr',
'ng-Static-Include',
'pageslide-directive',
'ngRutChange',
'xmsbsStopPropagation',
'ngEnter',
'ng-rut',
'ngMessages',
'duScroll',
'dynamicNumber',
'xmsbsDirectives',
'salfaDirectives',
'mgcrea.bootstrap.affix',
'fullPage.js',
'ui.tinymce',
'mega-menu',
'bootstrap.fileField',
'ngTagsInput'
]);
Partial view (home) trying to use the fullpage directive and generating the error:
<div class="section">
<div ng-style="{'width': '100%', 'height': vm.divHeight+'px'}" style="margin-top:-7px;background:url(/content/images/03.jpg) center center; background-size:cover;">
<div class="col-sm-12">
<h1 class="fg-grayLight text-center text-shadow vert-align-center" style="z-index:2;" ng-style="{'padding-top':vm.divHeight/9+'px'}">sistema de recursos humanos 2.0</h1>
</div>
</div>
</div>
<div class="section">
<div class="col-sm-12">
<h2 class="text-center">noticias</h2>
</div>
</div>
Affix directive:
'use strict';
angular.module('mgcrea.bootstrap.affix', ['mgcrea.jquery'])
.directive('bsAffix', function($window, dimensions) {
var checkPosition = function(instance, el, options) {
var scrollTop = window.pageYOffset;
var scrollHeight = document.body.scrollHeight;
var position = dimensions.offset.call(el[0]);
var height = dimensions.height.call(el[0]);
var offsetTop = options.offsetTop * 1;
var offsetBottom = options.offsetBottom * 1;
var reset = 'affix affix-top affix-bottom';
var affix;
if(instance.unpin !== null && (scrollTop + instance.unpin <= position.top)) {
affix = false;
} else if(offsetBottom && (position.top + height >= scrollHeight - offsetBottom)) {
affix = 'bottom';
} else if(offsetTop && scrollTop <= offsetTop) {
affix = 'top';
} else {
affix = false;
}
if (instance.affixed === affix) return;
instance.affixed = affix;
instance.unpin = affix === 'bottom' ? position.top - scrollTop : null;
el.removeClass(reset).addClass('affix' + (affix ? '-' + affix : ''));
};
var checkCallbacks = function(scope, instance, iElement, iAttrs) {
if(instance.affixed) {
if(iAttrs.onUnaffix)
eval("scope." + iAttrs.onUnaffix);
}
else {
if(iAttrs.onAffix)
eval("scope." + iAttrs.onAffix);
}
};
return {
restrict: 'EAC',
link: function postLink(scope, iElement, iAttrs) {
var instance = {unpin: null};
angular.element($window).bind('scroll', function() {
checkPosition(instance, iElement, iAttrs);
checkCallbacks(scope, instance, iElement, iAttrs);
});
angular.element($window).bind('click', function() {
setTimeout(function() {
checkPosition(instance, iElement, iAttrs);
checkCallbacks(scope, instance, iElement, iAttrs);
}, 1);
});
}
};
});
fullpage directive (this directive requires the original jQuery fullpage lugin to work http://www.alvarotrigo.com/fullPage/):
(function () {
'use strict';
angular
.module('fullPage.js', [])
.directive('fullPage', fullPage);
fullPage.$inject = ['$timeout'];
function fullPage($timeout) {
var directive = {
restrict: 'A',
scope: { options: '=' },
link: link
};
return directive;
function link(scope, element) {
var pageIndex;
var slideIndex;
var afterRender;
var onLeave;
var onSlideLeave;
if (typeof scope.options === 'object') {
if (scope.options.afterRender) {
afterRender = scope.options.afterRender;
}
if (scope.options.onLeave) {
onLeave = scope.options.onLeave;
}
if (scope.options.onSlideLeave) {
onSlideLeave = scope.options.onSlideLeave;
}
} else if (typeof options === 'undefined') {
scope.options = {};
}
var rebuild = function () {
destroyFullPage();
$(element).fullpage(sanatizeOptions(scope.options));
if (typeof afterRender === 'function') {
afterRender();
}
};
var destroyFullPage = function () {
if ($.fn.fullpage.destroy) {
$.fn.fullpage.destroy('all');
}
};
var sanatizeOptions = function (options) {
options.afterRender = afterAngularRender;
options.onLeave = onAngularLeave;
options.onSlideLeave = onAngularSlideLeave;
function afterAngularRender() {
//We want to remove the HREF targets for navigation because they use hashbang
//They still work without the hash though, so its all good.
if (options && options.navigation) {
$('#fp-nav').find('a').removeAttr('href');
}
if (pageIndex) {
$timeout(function () {
$.fn.fullpage.silentMoveTo(pageIndex, slideIndex);
});
}
}
function onAngularLeave(page, next, direction) {
if (typeof onLeave === 'function' && onLeave(page, next, direction) === false) {
return false;
}
pageIndex = next;
}
function onAngularSlideLeave(anchorLink, page, slide, direction, next) {
if (typeof onSlideLeave === 'function' && onSlideLeave(anchorLink, page, slide, direction, next) === false) {
return false;
}
pageIndex = page;
slideIndex = next;
}
//if we are using a ui-router, we need to be able to handle anchor clicks without 'href="#thing"'
$(document).on('click', '[data-menuanchor]', function () {
$.fn.fullpage.moveTo($(this).attr('data-menuanchor'));
});
return options;
};
var watchNodes = function () {
return element[0].getElementsByTagName('*').length;
};
scope.$watch(watchNodes, rebuild);
scope.$watch('options', rebuild, true);
element.on('$destroy', destroyFullPage);
}
}
})();

Does the second depends on the first one? If does, are you compiling the directive one before embedding the second?
If you have 'collision' it's means that you're using some sort of 'use strict', would be more valuable if you show part of the code and see if transclude is part of the directive.

Related

Directive in ng-repeat not re-processing after updating the array

I have a directive which converts certain strings into links (/) tags. I use this directive inside an ng-repeat to add links to text within a list of s. However, I refresh this data from a server which overwrites the array of the ng-repeat. The list gets updated in the DOM but the text no longer has links in it as it did when processed by the directive. How do I make the directive reprocess the text to add links?
Relevant code below
Controller HTML
<div ng-repeat="post in posts track by $index" ng-if="!post.deleted">
<div class="post wrap" ng-click="openSinglePostView(post, $index)" >
<div class="post-desc" linkify="twitter" ng-bind="post.desc"></div>
</div>
</div>
Controller JS
$scope.posts = [];
function refresh(){
$http.get(Constants.GET_POSTS_URL, {params : paramObject})
.then(function (response){
$scope.posts = [];
for(var i = 0; i < response.data.resultsArray.length; i++){
var post = new PostFactory(response.data.resultsArray[i]);
$scope.posts.push(post);
}
});
}
refresh();
Directive code
angular.module('linkify').directive('linkify', ['$filter', '$timeout', 'linkify', function ($filter, $timeout, linkify) {
'use strict';
return {
//restrict: 'A',
link: function (scope, element, attrs) {
var type = attrs.linkify || 'normal';
$timeout(function () { element.html(linkify[type](element.html()));
});
}
};
}]);
and for reference, the directive uses these filters and factories
angular.module('linkify')
.filter('linkify', function (Constants) {
'use strict';
function linkify (_str, type) {
if (!_str) {
return;
}
var _text = _str.replace( /(?:https?\:\/\/|www\.)+(?![^\s]*?")([\w.,#?!^=%&:\/~+#-]*[\w#?!^=%&\/~+#-])?/ig, function(url) {
var wrap = document.createElement('div');
var anch = document.createElement('a');
anch.href = url;
anch.target = "_blank";
anch.innerHTML = url;
wrap.appendChild(anch);
return wrap.innerHTML;
});
// bugfix
if (!_text) {
return '';
}
// Twitter
if (type === 'twitter') {
_text = _text.replace(/(|\s)*#([\u00C0-\u1FFF\w]+)/g, '$1#$2');
_text = _text.replace(/(^|\s)*#([\u00C0-\u1FFF\w]+)/g, '$1#$2');
}
return _text;
}
//
return function (text, type) {
return linkify(text, type);
};
})
.factory('linkify', ['$filter', function ($filter) {
'use strict';
function _linkifyAsType (type) {
return function (str) {(type, str);
return $filter('linkify')(str, type);
};
}
return {
twitter: _linkifyAsType('twitter'),
icon: _linkifyAsType('icon'),
normal: _linkifyAsType()
};
}])
Could the track by $index be the problem? Have you tried without it?

Angularjs, Range.insertNode, ngClick : After $compile Angular isn't aware of element - ngClick not working

ngClick is still not responding even after $compile. The new element is being applied to the DOM and is accessible via jQuery and JS. I assume that the issue is with the range.insertNode function. What am I missing here?
Here's my directive:
.directive('selectText', [
'$rootScope',
'$compile',
'$window',
function ($rootScope, $compile, $window) {
return {
restrict: 'A',
scope: {
hlid: "=",
tu: "="
},
link: function (scope, element, attrs) {
element.on('mouseup', function () {
//console.log("Attrs: "+JSON.stringify(attrs));
if ($window.getSelection().toString()) {
var text = $window.getSelection().toString();
if(text == '') {
console.log("No selection");
return;
}
var selection = $window.getSelection();
var range = selection.getRangeAt(0);
var selectionContents = range.extractContents();
var clk = "edSel('hl_"+scope.hlid+"','"+attrs.id+"');";
// var span = $compile(angular.element('<hlight id="hl_'+scope.hlid+'" class="cr-pr noselect clickable" title="Text Selection" ng-click="'+clk+'">'+text+'</hlight>'))(scope);
var span = angular.element($compile('<hlight id="hl_'+scope.hlid+'" class="cr-pr noselect clickable" title="Text Selection" ng-click="'+clk+'">'+text+'</hlight>')(scope));
console.log(span);
range.insertNode(span[0]);
scope.tu.target = element.html();
//selection.removeAllRanges();
var arr = {};
arr.action = 'add';
arr.tuid = attrs.id;
arr.hlid = 'hl_'+scope.hlid;
arr.content = element.html();
scope.$emit('hlChange', arr);
scope.hlid++;
console.log(element.html());
var modal = UIkit.modal("#hl_modal");
modal.show();
}
});
scope.edSel = function(id,tuid) {
console.log('ID: '+id+" - tuID: "+tuid);
}
}
};
}])
Thanks for any help

Angularjs responsive directive live updating issue (possibly due to ng-repeating the directive)

I am creating a post feed by ng-repeating JSON files from the cloud. I tried to make the posts responsive by using angular directives that update the template url with the screen size.
The problem is that only the last post in the ng-repeat responds and changes templates (with or without the reverse filter) when I resize the page. The other posts just remain the template that it was when originally loaded.
Here's the ng-repeat in the page
<div ng-show="post_loaded" ng-repeat="post in posts | reverse | filter:searchText ">
<feed-post>
</feed-post>
</div>
Here's the directive javascript file
app.directive('feedPost', function ($window) {
return {
restrict: 'E',
template: '<div ng-include="templateUrl"></div>',
link: function(scope) {
$window.onresize = function() {
changeTemplate();
scope.$apply();
};
changeTemplate();
function changeTemplate() {
var screenWidth = $window.innerWidth;
if (screenWidth < 768) {
scope.templateUrl = 'directives/post_mobile.html';
} else if (screenWidth >= 768) {
scope.templateUrl = 'directives/post_desktop.html';
}
}
}
};});
This happens because you re-assigning the .onresize in each directive and it stays effective only for the last linked directive.
I'd suggest to use it in a more angular way. You don't actually need a custom directive
In the controller that manages list of posts add reference to $window in $scope
$scope.window = $window;
Then in template make use of it
<div ng-include="directives/post_mobile.html" ng-if="window.innerWidth < 768"></div>
<div ng-include="directives/post_desktop.html" ng-if="window.innerWidth >= 768"></div>
To avoid extra wrappers for posts feed you might want to use ng-repeat-start, ng-repeat-end directives
this is a directive i wrote based on bootstrap sizes and ngIf directive :
mainApp.directive("responsive", function($window, $animate) {
return {
restrict: "A",
transclude: 'element',
terminal: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
//var val = $attr["responsive"];
var block, childScope;
$scope.$watch(function(){ return $window.innerWidth; }, function (width) {
if (width < 768) {
var s = "xs";
} else if (width < 992) {
var s = "sm";
} else if (width < 1200) {
var s = "md";
} else {
var s = "lg";
}
console.log("responsive ok?", $attr.responsive == s);
if ($attr.responsive == s) {
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end responsive: ' + $attr.responsive + ' ');
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
} else {
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
block.clone.remove();
block.clone = null;
block = null;
}
}
});
}
};
});

Decorating a directive by adding a function that will call the directive's controller

I use a directive that is declared like this :
(function (directives) {
var FilterDirective = (function () {
function FilterDirective() {
var directive = {};
directive.restrict = 'A';
directive.scope = true;
directive.controller = elasticui.controllers.FilterController;
directive.link = function (scope, element, attrs, filterCtrl) {
scope.$watch(element.attr('eui-filter') + " | euiCached", function (val) { return scope.filter.filter = val; });
var enabled = false;
var enabledAttr = element.attr('eui-enabled');
if (enabledAttr) {
scope.$watch(enabledAttr, function (val) { return scope.filter.enabled = val; });
enabled = scope.$eval(enabledAttr);
}
scope.filter = {
filter: scope.$eval(element.attr('eui-filter') + " | euiCached"),
enabled: enabled
};
filterCtrl.init();
};
return directive;
}
return FilterDirective;
})();
directives.FilterDirective = FilterDirective;
directives.directives.directive('euiFilter', FilterDirective);
})
The controller of the directive is :
(function (controllers) {
var FilterController = (function () {
function FilterController($scope) {
this.scope = $scope;
}
FilterController.prototype.init = function () {
var _this = this;
if (this.scope.filter.filter) {
var isEnabled = this.scope.filters.contains(this.scope.filter.filter);
if (!isEnabled && this.scope.filter.enabled) {
this.scope.filters.add(this.scope.filter.filter);
isEnabled = true;
}
}
this.scope.filter.enabled = isEnabled;
this.scope.$watch('filter.enabled', function (newVal, oldVal) {
if (newVal !== oldVal) {
_this.updateFilter();
}
});
this.scope.$watch('filter.filter', function (newVal, oldVal) {
if (!elasticui.util.EjsTool.equals(oldVal, newVal)) {
if (oldVal) {
_this.scope.filters.remove(oldVal);
}
_this.updateFilter();
}
});
};
FilterController.prototype.updateFilter = function () {
if (!this.scope.filter.filter) {
return;
}
if (this.scope.filter.enabled) {
this.scope.filters.add(this.scope.filter.filter);
}
else {
this.scope.filters.remove(this.scope.filter.filter);
}
};
FilterController.$inject = ['$scope'];
return FilterController;
})();
controllers.FilterController = FilterController;
})
Actually, the directive has a scope containing a filter object which contains two attributes filter : { enabled : boolean, filter : object} and the directive is used like this :
<label class="btn" ng-model="filter.enabled"
eui-filter="ejs.TermFilter('field','value')" btn-checkbox>
when the button is clicked the filter.enabled is set. My purpose is to add a behavior that will permit to change filter.enabled value via a function external to the directive.
The directive will look like this :
<label class="btn" ng-model="filter.enabled"
eui-filter="ejs.TermFilter('field','value')" eui-enable-fn="fn(somevariable)" btn-checkbox>
where fn will take the somevariable and set it to the filter.enabled.
Thanks in advance,
If you want to enable/disable a filter through the pressure of a button why not declare a filter with the property eui-enabled set to a custom toggling variable?
In other words it would result as:
HTML:
<label class="btn" eui-filter="..." eui-enabled="my_toggling_variable">
<button type=button ng-click="toggleVar()"></button>
JS:
myApp.controller('myCtrl', ['$scope', function($scope) {
$scope.my_toggling_variable = false;
$scope. toggleVar = function(){
$scope.my_toggling_variable = !$scope.my_toggling_variable;
};
}]);
Hope to have understood well the topic.

How to dismiss an angularjs alert when user changes route/state

I am using this angular js service/directive github pageto display alerts. An issue has been opened relating to the question I am asking but it has not been addressed by the developer.
i want first alert shown when user logs in to disappear when the user clicks logout but the alerts are stacking up on top of each other.
Here is a fiddle although I could not replicate the issue but it shows the structure of my code. fiddle
html:
<body ng-app="app">
<mc-messages></mc-messages>
<button ng-click="login()">Login</button>
<button ng-click="logout()">Logout</button>
</body>
js:
/*jshint strict:false */
'use strict';
var app = angular.module('app', ['MessageCenterModule']);
app.controller(function ($scope, messageCenterService, $location) {
$scope.login = function () {
$location.path('/');
messageCenterService.add('success',
'You are now loggedin!', {
status: messageCenterService.status.next
});
};
$scope.logout = function () {
$location.path('login');
messageCenterService.add('success',
'You are now loggedout!', {
status: messageCenterService.status.next
}
};
});
// Create a new angular module.
var MessageCenterModule = angular.module('MessageCenterModule', []);
// Define a service to inject.
MessageCenterModule.
service('messageCenterService', ['$rootScope', '$sce', '$timeout',
function ($rootScope, $sce, $timeout) {
return {
mcMessages: this.mcMessages || [],
status: {
unseen: 'unseen',
shown: 'shown',
/** #var Odds are that you will show a message and right after that
* change your route/state. If that happens your message will only be
* seen for a fraction of a second. To avoid that use the "next"
* status, that will make the message available to the next page */
next: 'next',
/** #var Do not delete this message automatically. */
permanent: 'permanent'
},
add: function (type, message, options) {
var availableTypes = ['info', 'warning', 'danger', 'success'],
service = this;
options = options || {};
if (availableTypes.indexOf(type) === -1) {
throw "Invalid message type";
}
var messageObject = {
type: type,
status: options.status || this.status.unseen,
processed: false,
close: function () {
return service.remove(this);
}
};
messageObject.message = options.html ? $sce.trustAsHtml(message) : message;
messageObject.html = !! options.html;
if (angular.isDefined(options.timeout)) {
messageObject.timer = $timeout(function () {
messageObject.close();
}, options.timeout);
}
this.mcMessages.push(messageObject);
return messageObject;
},
remove: function (message) {
var index = this.mcMessages.indexOf(message);
this.mcMessages.splice(index, 1);
},
reset: function () {
this.mcMessages = [];
},
removeShown: function () {
for (var index = this.mcMessages.length - 1; index >= 0; index--) {
if (this.mcMessages[index].status == this.status.shown) {
this.remove(this.mcMessages[index]);
}
}
},
markShown: function () {
for (var index = this.mcMessages.length - 1; index >= 0; index--) {
if (!this.mcMessages[index].processed) {
if (this.mcMessages[index].status == this.status.unseen) {
this.mcMessages[index].status = this.status.shown;
} else if (this.mcMessages[index].status == this.status.next) {
this.mcMessages[index].status = this.status.unseen;
}
this.mcMessages[index].processed = true;
}
}
},
flush: function () {
$rootScope.mcMessages = this.mcMessages;
}
};
}]);
MessageCenterModule.
directive('mcMessages', ['$rootScope', 'messageCenterService', function ($rootScope, messageCenterService) {
/*jshint multistr: true */
var templateString = '\
<div id="mc-messages-wrapper">\
<div class="alert alert-{{ message.type }} {{ animation }}" ng-repeat="message in mcMessages">\
<a class="close" ng-click="message.close();" data-dismiss="alert" aria-hidden="true">×</a>\
<span ng-switch on="message.html">\
<span ng-switch-when="true">\
<span ng-bind-html="message.message"></span>\
</span>\
<span ng-switch-default>\
{{ message.message }}\
</span>\
</div>\
</div>\
';
return {
restrict: 'EA',
template: templateString,
link: function (scope, element, attrs) {
// Bind the messages from the service to the root scope.
messageCenterService.flush();
var changeReaction = function (event, to, from) {
// Update 'unseen' messages to be marked as 'shown'.
messageCenterService.markShown();
// Remove the messages that have been shown.
messageCenterService.removeShown();
$rootScope.mcMessages = messageCenterService.mcMessages;
messageCenterService.flush();
};
$rootScope.$on('$locationChangeStart', changeReaction);
scope.animation = attrs.animation || 'fade in';
}
};
}]);
Hope this is clear enough for someone to help me. If not let me know and I can try to clarify.

Resources