I'm new to AngularJS. I'm using AngularJS 1.2.5 and Bootstrap 3.0. I'm trying to include ScrollSpy in my app. However, I'm having some challenges. I'm trying to incorporate the code found here. Currently, my code looks like this:
index.html
<div class="row" scroll-spy>
<div class="col-md-3 sidebar">
<ul style="position:fixed;" class="nav nav-pills nav-stacked">
<li class="active" spy="overview">Overview</li>
<li spy="main">Main Content</li>
<li spy="summary">Summary</li>
<li spy="links">Other Links</li>
</ul>
</div>
<div class="col-md-9 content">
<h3 id="overview">Overview</h3>
Lorem Ipsum Text goes here...
<h3 id="main">Main Body</h3>
Lorem Ipsum Text goes here...
<h3 id="summary">Summary</h3>
Lorem Ipsum text goes here...
<h3 id="links">Other Links</h3>
</div>
</div>
index.html.js
angular.module('td.controls.scrollSpy', [])
.directive('spy', function ($location) {
return {
restrict: 'A',
require: '^scrollSpy',
link: function (scope, elem, attrs, scrollSpy) {
var _ref;
if ((_ref = attrs.spyClass) == null) {
attrs.spyClass = 'current';
}
elem.click(function () {
return scope.$apply(function () {
return $location.hash(attrs.spy);
});
});
return scrollSpy.addSpy({
id: attrs.spy,
'in': function () {
return elem.addClass(attrs.spyClass);
},
out: function () {
return elem.removeClass(attrs.spyClass);
}
});
}
};
})
.directive('scrollSpy', function ($location) {
return {
restrict: 'A',
controller: function ($scope) {
$scope.spies = [];
return this.addSpy = function (spyObj) {
return $scope.spies.push(spyObj);
};
},
link: function (scope, elem, attrs) {
var spyElems;
spyElems = [];
scope.$watch('spies', function (spies) {
var spy, _i, _len, _results;
_results = [];
for (_i = 0, _len = spies.length; _i < _len; _i++) {
spy = spies[_i];
if (spyElems[spy.id] == null) {
_results.push(spyElems[spy.id] = elem.find('#' + spy.id));
} else {
_results.push(void 0);
}
}
return _results;
});
return $($window).scroll(function () {
var highlightSpy, pos, spy, _i, _len, _ref;
highlightSpy = null;
_ref = scope.spies;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
spy = _ref[_i];
spy.out();
spyElems[spy.id] = spyElems[spy.id].length === 0 ? elem.find('#' + spy.id) : spyElems[spy.id];
if (spyElems[spy.id].length !== 0) {
if ((pos = spyElems[spy.id].offset().top) - $window.scrollY <= 0) {
spy.pos = pos;
if (highlightSpy == null) {
highlightSpy = spy;
}
if (highlightSpy.pos < spy.pos) {
highlightSpy = spy;
}
}
}
}
return highlightSpy != null ? highlightSpy['in']() : void 0;
});
}
};
})
;
When I run this in the browser I get several errors. When I initially run it, I see the following errors in my browser console:
TypeError: Object function (spyObj) { return $scope.spies.push(spyObj); } has no method 'addSpy'
ReferenceError: $window is not defined
I can't figure out a) Why I'm getting these errors or b) how to get this basic example to work. I really like this approach to using scrollspy with AngularJS. It's the cleanest implementation I've seen. For that reason, I'd love to figure out how to get this working.
I recently ran across Alexander's solution as well and went through the process of translating it.
To answer your direct question: You need to import $window into your scrollSpy directive.
.directive('scrollSpy', function ($location, $window) {
Below is the complete translation I did of Alexander's code:
app.directive('scrollSpy', function ($window) {
return {
restrict: 'A',
controller: function ($scope) {
$scope.spies = [];
this.addSpy = function (spyObj) {
$scope.spies.push(spyObj);
};
},
link: function (scope, elem, attrs) {
var spyElems;
spyElems = [];
scope.$watch('spies', function (spies) {
var spy, _i, _len, _results;
_results = [];
for (_i = 0, _len = spies.length; _i < _len; _i++) {
spy = spies[_i];
if (spyElems[spy.id] == null) {
_results.push(spyElems[spy.id] = elem.find('#' + spy.id));
}
}
return _results;
});
$($window).scroll(function () {
var highlightSpy, pos, spy, _i, _len, _ref;
highlightSpy = null;
_ref = scope.spies;
// cycle through `spy` elements to find which to highlight
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
spy = _ref[_i];
spy.out();
// catch case where a `spy` does not have an associated `id` anchor
if (spyElems[spy.id].offset() === undefined) {
continue;
}
if ((pos = spyElems[spy.id].offset().top) - $window.scrollY <= 0) {
// the window has been scrolled past the top of a spy element
spy.pos = pos;
if (highlightSpy == null) {
highlightSpy = spy;
}
if (highlightSpy.pos < spy.pos) {
highlightSpy = spy;
}
}
}
// select the last `spy` if the scrollbar is at the bottom of the page
if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
spy.pos = pos;
highlightSpy = spy;
}
return highlightSpy != null ? highlightSpy["in"]() : void 0;
});
}
};
});
app.directive('spy', function ($location, $anchorScroll) {
return {
restrict: "A",
require: "^scrollSpy",
link: function(scope, elem, attrs, affix) {
elem.click(function () {
$location.hash(attrs.spy);
$anchorScroll();
});
affix.addSpy({
id: attrs.spy,
in: function() {
elem.addClass('active');
},
out: function() {
elem.removeClass('active');
}
});
}
};
});
The above code also supports highlight the last spy element in the menu if the browser is scrolled to the bottom, which the original code did not.
if you wont that it working with ng-include change the follow condition
if (spyElems[spy.id].offset() === undefined) {
continue;
}
on this
if (spyElems[spy.id].offset() === undefined) {
// try to refind it
spyElems[spy.id] = elem.find('#' + spy.id);
if(spyElems[spy.id].offset() === undefined)
continue;
}
Related
//when open application then this error show, How can i fix this please explain me.
TypeError: keyboard[extension] is not a function
at Object.attach (ng-virtual-keyboard.js:104)
at Object.link (ng-virtual-keyboard.js:133)
at angular.js:1365
at angular.js:11229
at invokeLinkFn (angular.js:11235)
at nodeLinkFn (angular.js:10554)
at compositeLinkFn (angular.js:9801)
at nodeLinkFn (angular.js:10548)
at compositeLinkFn (angular.js:9801)
at compositeLinkFn (angular.js:9804)
"<input type="text" id="login" name="login" ng-virtual-keyboard="" placeholder="Employee ID" class="fadeIn second ng-pristine ng-untouched ng-valid ng-isolate-scope ui-keyboard-input ui-widget-content ui-corner-all" ng-model="auth.empID" required="" aria-haspopup="true" role="textbox">"
// This is HTML code
<input type="text"id="login"name="login" ng-virtual-keyboard placeholder="Employee ID" class="fadeIn second" ng-model="auth.empID" required>
<input type="password" id="password" ng-virtual-keyboard placeholder="Password" class="fadeIn third" ng-model= "auth.password" required>
<input ng-click="signin(auth)" type="submit" class="fadeIn fourth" value="Log In">
// this is my function in angularjs
$scope.signin = function(valid){
if(valid){
var sign = customerService.validUser($scope.auth);
sign.then(function(data){
if(data.status == "success"){
$scope.val = data;
$localStorage.val = data;
if(data.userdata.usertype == "admin"){
$location.path("/admin");
$rootScope.$emit("callAdmin", {"mydata":data});
}else if(data.userdata.usertype == "user"){
$location.path("/product");
$rootScope.$emit("callClient", {"mydata":data});
}
toastr.info("Welcome !");
}else{
toastr.error("Invalid Credential !");
}
})
}else{
toastr.error("Invalid Credential !");
}
};
//this is ng-virtual-keyboard.js
/**
* ng-virtual-keyboard
* An AngularJs Virtual Keyboard Interface based on Mottie/Keyboard
* #version v0.3.3
* #author antonio-spinelli
* #link https://github.com/antonio-spinelli/ng-virtual-keyboard
* #license MIT
*/
(function (angular) {
angular.module('ng-virtual-keyboard', [])
.constant('VKI_CONFIG', {
})
.service('ngVirtualKeyboardService', ['VKI_CONFIG', function(VKI_CONFIG) {
var clone = function(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null === obj || 'object' !== typeof obj) {
return obj;
}
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = clone(obj[attr]);
}
}
return copy;
}
throw new Error('Unable to copy obj! Its type isn\'t supported.');
};
var executeGetKeyboard = function(elementReference) {
var keyboard;
var element = $(elementReference);
if (element) {
keyboard = $(elementReference).getkeyboard();
}
return keyboard;
};
return {
attach: function(element, config, inputCallback) {
var newConfig = clone(VKI_CONFIG);
config = config || {};
for (var attr in config) {
if (config.hasOwnProperty(attr)) {
newConfig[attr] = config[attr];
}
}
newConfig.accepted = config.accepted || inputCallback;
if (config.autoUpdateModel) {
newConfig.change = config.change || inputCallback;
}
if (newConfig.events) {
var addEventMethod = function(eventName) {
return function(e, kb, el) {
newConfig.events[eventName](e, $(this).data('keyboard'), this);
};
};
for (var eventName in newConfig.events) {
$(element).on(eventName, addEventMethod(eventName));
}
}
var keyboard = $(element).keyboard(newConfig);
if (keyboard && newConfig.extensions) {
for (var extension in newConfig.extensions) {
var extConfig = newConfig.extensions[extension];
if (extConfig) {
keyboard[extension](extConfig);
} else {
keyboard[extension]();
}
}
}
},
getKeyboard: function(elementReference) {
return executeGetKeyboard(elementReference);
},
getKeyboardById: function(id) {
return executeGetKeyboard('#' + id);
}
};
}])
.directive('ngVirtualKeyboard', ['ngVirtualKeyboardService', '$timeout',
function(ngVirtualKeyboardService, $timeout) {
return {
restrict: 'A',
require: '?ngModel',
scope: {
config: '=ngVirtualKeyboard'
},
link: function(scope, elements, attrs, ngModelCtrl) {
var element = elements[0];
if (!ngModelCtrl || !element) {
return;
}
ngVirtualKeyboardService.attach(element, scope.config, function(e, kb, el) {
$timeout(function() {
ngModelCtrl.$setViewValue(element.value);
});
});
scope.$on('$destroy', function() {
var keyboard = $(element).getkeyboard();
if (keyboard) {
keyboard.destroy();
}
});
}
};
}
]);
})(angular);
/**
* ng-virtual-keyboard
* An AngularJs Virtual Keyboard Interface based on Mottie/Keyboard
* #version v0.3.3
* #author antonio-spinelli <antonio.86.spinelli#gmail.com>
* #link https://github.com/antonio-spinelli/ng-virtual-keyboard
* #license MIT
*/
(function (angular) {
angular.module('ng-virtual-keyboard', [])
.constant('VKI_CONFIG', {
})
.service('ngVirtualKeyboardService', ['VKI_CONFIG', function(VKI_CONFIG) {
var clone = function(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null === obj || 'object' !== typeof obj) {
return obj;
}
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = clone(obj[attr]);
}
}
return copy;
}
throw new Error('Unable to copy obj! Its type isn\'t supported.');
};
var executeGetKeyboard = function(elementReference) {
var keyboard;
var element = $(elementReference);
if (element) {
keyboard = $(elementReference).getkeyboard();
}
return keyboard;
};
return {
attach: function(element, config, inputCallback) {
var newConfig = clone(VKI_CONFIG);
config = config || {};
for (var attr in config) {
if (config.hasOwnProperty(attr)) {
newConfig[attr] = config[attr];
}
}
newConfig.accepted = config.accepted || inputCallback;
if (config.autoUpdateModel) {
newConfig.change = config.change || inputCallback;
}
if (newConfig.events) {
var addEventMethod = function(eventName) {
return function(e, kb, el) {
newConfig.events[eventName](e, $(this).data('keyboard'), this);
};
};
for (var eventName in newConfig.events) {
$(element).on(eventName, addEventMethod(eventName));
}
}
var keyboard = $(element).keyboard(newConfig);
if (keyboard && newConfig.extensions) {
for (var extension in newConfig.extensions) {
var extConfig = newConfig.extensions[extension];
if (extConfig) {
keyboard[extension](extConfig);
} else {
//keyboard[extension]();
}
}
}
},
getKeyboard: function(elementReference) {
return executeGetKeyboard(elementReference);
},
getKeyboardById: function(id) {
return executeGetKeyboard('#' + id);
}
};
}])
.directive('ngVirtualKeyboard', ['ngVirtualKeyboardService', '$timeout',
function(ngVirtualKeyboardService, $timeout) {
return {
restrict: 'A',
require: '?ngModel',
scope: {
config: '=ngVirtualKeyboard'
},
link: function(scope, elements, attrs, ngModelCtrl) {
var element = elements[0];
if (!ngModelCtrl || !element) {
return;
}
ngVirtualKeyboardService.attach(element, scope.config, function(e, kb, el) {
$timeout(function() {
ngModelCtrl.$setViewValue(element.value);
});
});
scope.$on('$destroy', function() {
var keyboard = $(element).getkeyboard();
if (keyboard) {
keyboard.destroy();
}
});
}
};
}
]);
})(angular);
****Its working well, i am just comment following line***
//keyboardextension;
but am i right? please answer me !!
My html code is as follows.
<div class="panel-heading">
Select areas to be visited by the operator
<multiselect ng-model="selection" options="areanames" show-search="true"></multiselect>
</div>
My application's controller code is as follows. The function getArea is being called when a user inputs some details in the form (not included here).
this.getArea = function(){
$scope.areanames = [];
$http({
method: "GET",
url: "http://xx.xx.xx.xx/abc",
params:{city:$scope.city,circle:$scope.circle}
}).then(function(success){
for (i = 0; i < success.data.length; i++)
$scope.areanames.push(success.data[i].area);
},function(error){
console.log('error ' + JSON.stringify(error));
});
}
The directive multiselect is written as follows.
multiselect.directive('multiselect', ['$filter', '$document', '$log', function ($filter, $document, $log) {
return {
restrict: 'AE',
scope: {
options: '=',
displayProp: '#',
idProp: '#',
searchLimit: '=?',
selectionLimit: '=?',
showSelectAll: '=?',
showUnselectAll: '=?',
showSearch: '=?',
searchFilter: '=?',
disabled: '=?ngDisabled'
},
replace:true,
require: 'ngModel',
templateUrl: 'multiselect.html',
link: function ($scope, $element, $attrs, $ngModelCtrl) {
$scope.selectionLimit = $scope.selectionLimit || 0;
$scope.searchLimit = $scope.searchLimit || 25;
$scope.searchFilter = '';
if (typeof $scope.options !== 'function') {
$scope.resolvedOptions = $scope.options;
}
if (typeof $attrs.disabled != 'undefined') {
$scope.disabled = true;
}
$scope.toggleDropdown = function () {
console.log('toggleDown');
$scope.open = !$scope.open;
};
var closeHandler = function (event) {
console.log('closeHandler');
if (!$element[0].contains(event.target)) {
$scope.$apply(function () {
$scope.open = false;
});
}
};
$document.on('click', closeHandler);
var updateSelectionLists = function () {
console.log('updateSelectionList');
if (!$ngModelCtrl.$viewValue) {
if ($scope.selectedOptions) {
$scope.selectedOptions = [];
}
$scope.unselectedOptions = $scope.resolvedOptions.slice(); // Take a copy
} else {
$scope.selectedOptions = $scope.resolvedOptions.filter(function (el) {
var id = $scope.getId(el);
for (var i = 0; i < $ngModelCtrl.$viewValue.length; i++) {
var selectedId = $scope.getId($ngModelCtrl.$viewValue[i]);
if (id === selectedId) {
return true;
}
}
return false;
});
$scope.unselectedOptions = $scope.resolvedOptions.filter(function (el) {
return $scope.selectedOptions.indexOf(el) < 0;
});
}
};
$ngModelCtrl.$render = function () {
console.log('render called');
updateSelectionLists();
};
$ngModelCtrl.$viewChangeListeners.push(function () {
console.log('viewChangeListener');
updateSelectionLists();
});
$ngModelCtrl.$isEmpty = function (value) {
console.log('isEmpty');
if (value) {
return (value.length === 0);
} else {
return true;
}
};
var watcher = $scope.$watch('selectedOptions', function () {
$ngModelCtrl.$setViewValue(angular.copy($scope.selectedOptions));
}, true);
$scope.$on('$destroy', function () {
console.log('destroy');
$document.off('click', closeHandler);
if (watcher) {
watcher(); // Clean watcher
}
});
$scope.getButtonText = function () {
console.log('getButtonText');
if ($scope.selectedOptions && $scope.selectedOptions.length === 1) {
return $scope.getDisplay($scope.selectedOptions[0]);
}
if ($scope.selectedOptions && $scope.selectedOptions.length > 1) {
var totalSelected;
totalSelected = angular.isDefined($scope.selectedOptions) ? $scope.selectedOptions.length : 0;
if (totalSelected === 0) {
return 'Select';
} else {
return totalSelected + ' ' + 'selected';
}
} else {
return 'Select';
}
};
$scope.selectAll = function () {
console.log('selectAll');
$scope.selectedOptions = $scope.resolvedOptions;
$scope.unselectedOptions = [];
};
$scope.unselectAll = function () {
console.log('unSelectAll');
$scope.selectedOptions = [];
$scope.unselectedOptions = $scope.resolvedOptions;
};
$scope.toggleItem = function (item) {
console.log('toggleItem');
if (typeof $scope.selectedOptions === 'undefined') {
$scope.selectedOptions = [];
}
var selectedIndex = $scope.selectedOptions.indexOf(item);
var currentlySelected = (selectedIndex !== -1);
if (currentlySelected) {
$scope.unselectedOptions.push($scope.selectedOptions[selectedIndex]);
$scope.selectedOptions.splice(selectedIndex, 1);
} else if (!currentlySelected && ($scope.selectionLimit === 0 || $scope.selectedOptions.length < $scope.selectionLimit)) {
var unselectedIndex = $scope.unselectedOptions.indexOf(item);
$scope.unselectedOptions.splice(unselectedIndex, 1);
$scope.selectedOptions.push(item);
}
};
$scope.getId = function (item) {
console.log('getID');
if (angular.isString(item)) {
return item;
} else if (angular.isObject(item)) {
if ($scope.idProp) {
return multiselect.getRecursiveProperty(item, $scope.idProp);
} else {
$log.error('Multiselect: when using objects as model, a idProp value is mandatory.');
return '';
}
} else {
return item;
}
};
$scope.getDisplay = function (item) {
console.log('getDisplay');
if (angular.isString(item)) {
return item;
} else if (angular.isObject(item)) {
if ($scope.displayProp) {
return multiselect.getRecursiveProperty(item, $scope.displayProp);
} else {
$log.error('Multiselect: when using objects as model, a displayProp value is mandatory.');
return '';
}
} else {
return item;
}
};
$scope.isSelected = function (item) {
console.log('isSelected');
if (!$scope.selectedOptions) {
return false;
}
var itemId = $scope.getId(item);
for (var i = 0; i < $scope.selectedOptions.length; i++) {
var selectedElement = $scope.selectedOptions[i];
if ($scope.getId(selectedElement) === itemId) {
return true;
}
}
return false;
};
$scope.updateOptions = function () {
console.log('updateOptions');
if (typeof $scope.options === 'function') {
$scope.options().then(function (resolvedOptions) {
$scope.resolvedOptions = resolvedOptions;
updateSelectionLists();
});
}
};
// This search function is optimized to take into account the search limit.
// Using angular limitTo filter is not efficient for big lists, because it still runs the search for
// all elements, even if the limit is reached
$scope.search = function () {
console.log('search');
var counter = 0;
return function (item) {
if (counter > $scope.searchLimit) {
return false;
}
var displayName = $scope.getDisplay(item);
if (displayName) {
var result = displayName.toLowerCase().indexOf($scope.searchFilter.toLowerCase()) > -1;
if (result) {
counter++;
}
return result;
}
}
};
}
};
}]);
When areanames is getting updated asynchronously its values are not getting displayed in multiselect. The inner scope's options value is becoming undefined though I am using '=' with same attribute name i.e., options in the html code.
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.
I am using a directive for auto complete / auto suggest in angular Js taken from http://demo.jankuri.com/ngAutocomplete/. It is working fine getting the data from server and filtering it. But I am facing problem into select and use that select item from the auto complete.
Here is the code of directive what I am using for this...
app.factory('ngAutocompleteService', ['$http', function($http)
{
var self = this;
self.getData = function (url, keyword) {
return $http.get(url, { query: keyword });
};
return self;
}])
app.directive('ngAutocomplete', ['$timeout','$filter','ngAutocompleteService',
function($timeout, $filter, ngAutocompleteService)
{
'use strict';
var keys = {
left : 37,
up : 38,
right : 39,
down : 40,
enter : 13,
esc : 27
};
var setScopeValues = function (scope, attrs) {
scope.url = base_url+attrs.url || null;
scope.searchProperty = attrs.searchProperty || 'skills';
scope.maxResults = attrs.maxResults || 10;
scope.delay = parseInt(attrs.delay, 10) || 300;
scope.minLenth = parseInt(attrs.minLenth, 10) || 2;
scope.allowOnlyResults = scope.$eval(attrs.allowOnlyResults) || false;
scope.placeholder = attrs.placeholder || 'Search...';
};
var delay = (function() {
var timer = 0;
return function (callback, ms) {
$timeout.cancel(timer);
timer = $timeout(callback, ms);
};
})();
return {
restrict: 'E',
require: '?ngModel',
scope: true,
link: function(scope, element, attrs, ngModel) {
setScopeValues(scope, attrs);
scope.results = [];
scope.currentIndex = null;
scope.getResults = function () {
if (parseInt(scope.keyword.length, 10) === 0) scope.results = [];
if (scope.keyword.length < scope.minLenth) return;
delay(function() {
ngAutocompleteService.getData(scope.url, scope.keyword).then(function(resp) {
scope.results = [];
var filtered = $filter('filter')(resp.data, {skills: scope.keyword});
for (var i = 0; i < scope.maxResults; i++) {
scope.results.push(filtered[i]);
}
scope.currentIndex = 0;
if (scope.results.length) {
scope.showResults = true;
}
});
}, scope.delay);
};
scope.selectResult = function (r) {
scope.keyword = r.skills;
ngModel.$setViewValue(r.skills);
scope.ngModel = r.skills;
ngModel.$render();
scope.showResults = false;
};
scope.clearResults = function () {
scope.results = [];
scope.currentIndex = null;
};
scope.hoverResult = function (i) {
scope.currentIndex = i;
}
scope.blurHandler = function () {
$timeout(function() {
if (scope.allowOnlyResults) {
var find = $filter('filter')(scope.results, {skills: scope.keyword}, true);
if (!find.length) {
scope.keyword = '';
ngModel.$setViewValue('');
}
}
scope.showResults = false;
}, 100);
};
scope.keyupHandler = function (e) {
var key = e.which || e.keyCode;
if (key === keys.enter) {
scope.selectResult(scope.results[scope.currentIndex]);
}
if (key === keys.left || key === keys.up) {
if (scope.currentIndex > 0) {
scope.currentIndex -= 1;
}
}
if (key === keys.right || key === keys.down) {
if (scope.currentIndex < scope.maxResults - 1) {
scope.currentIndex += 1;
}
}
if (key === keys.esc) {
scope.keyword = '';
ngModel.$setViewValue('');
scope.clearResults();
}
};
},
template:
'<input type="text" class="form-control" ng-model="keyword" placeholder="{{placeholder}}" ng-change="getResults()" ng-keyup="keyupHandler($event)" ng-blur="blurHandler()" ng-focus="currentIndex = 0" autocorrect="off" autocomplete="off">' +
'<input type="hidden" ng-model="skillIdToBeRated">'+
'<div ng-show="showResults">' +
' <div ng-repeat="r in results | filter : {skills: keyword}" ng-click="selectResult(r)" ng-mouseover="hoverResult($index)" ng-class="{\'hover\': $index === currentIndex}">' +
' <span class="form-control">{{ r.skills }}</span>' +
' </div>' +
'</div>'
};
}]);
I am unable to get value which is selected by ng-click="selectResult(r)" function. The value is showing into text field but not getting it into controller.
I was also using the same directive for showing the auto complete text box. I have tried the following for getting the selected value from auto complete.
in HTML
<div ng-controller="Cntrl as cntrl">
<ng-autocomplete ng-model="cntrl.selectedValue" url="url" search-property="keyword" max-results="10" delay="300" min-length="2" allow-only-results="true"></ng-autocomplete>
</div>
in JavaScript
app.controller('Cntrl', function($scope, $http) {
var self = this;
self.selectedValue = '';
$scope.getSelectedValue = function(){
console.log(self.selectedValue);
}
});
I hope this may help you.
I ran into the same issue. I ended up just watching the property from the details attribute in the ng-autocomplete input and it works pretty well.
$scope.$watch(function() {
return vm.location_result;
}, function(location) {
if (location) {
vm.location_list.push(location);
vm.location = '';
}
});
Fiddle Example: http://jsfiddle.net/n3ztwucL/
GitHub Gist: https://gist.github.com/robrothedev/46e1b2a2470b1f8687ad
I am trying to make a alert service with a directive. It is in the directive part I have some trouble. My have a directive that looks like this:
angular.module('alertModule').directive('ffAlert', function() {
return {
templateUrl: 'components/alert/ff-alert-directive.html',
controller: ['$scope','alertService',function($scope,alertService) {
$scope.alerts = alertService;
}],
link: function (scope, elem, attrs, ctrl) {
scope.$watch(scope.alerts, function (newValue, oldValue) {
console.log("alerts is now:",scope.alerts,oldValue, newValue);
for(var i = oldValue.list.length; i < newValue.list.length; i++) {
scope.alerts.list[i].isVisible = true;
if (scope.alerts.list[i].timeout > 0) {
$timeout(function (){
scope.alerts.list[i].isVisible = false;
}, scope.alerts.list[i].timeout);
}
}
}, true);
}
}
});
The reason for the for-loop is to attach a timeout for the alerts that has this specified.
I will also include the directive-template:
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-10">
<div alert ng-repeat="alert in alerts.list" type="{{alert.type}}" ng-show="alert.isVisible" close="alerts.close(alert.id)">{{alert.msg}}</div>
</div>
<div class="col-sm-1"></div>
</div>
When I run this, I get this error in the console:
TypeError: Cannot read property 'list' of undefined
at Object.fn (http://localhost:9000/components/alert/ff-alert-directive.js:10:29)
10:29 is the dot in "oldValue.list" in the for-loop. Any idea what I am doing wrong?
Edit: I am adding the alertService-code (it is a service I use to keep track of all the alerts in my app):
angular.module('alertModule').factory('alertService', function() {
var alerts = {};
var id = 1;
alerts.list = [];
alerts.add = function(alert) {
alert.id = id;
alerts.list.push(alert);
alert.id += 1;
console.log("alertService.add: ",alert);
return alert.id;
};
alerts.add({type: "info", msg:"Dette er til info...", timeout: 1000});
alerts.addServerError = function(error) {
var id = alerts.add({type: "warning", msg: "Errormessage from server: " + error.description});
// console.log("alertService: Server Error: ", error);
return id;
};
alerts.close = function(id) {
for(var index = 0; index<alerts.list.length; index += 1) {
console.log("alert:",index,alerts.list[index].id);
if (alerts.list[index].id == id) {
console.log("Heey");
alerts.list.splice(index, 1);
}
}
};
alerts.closeAll = function() {
alerts.list = [];
};
return alerts;
});
try like this , angular fires your watcher at the first time when your directive initialized
angular.module('alertModule').directive('ffAlert', function() {
return {
templateUrl: 'components/alert/ff-alert-directive.html',
controller: ['$scope','alertService',function($scope,alertService) {
$scope.alerts = alertService;
}],
link: function (scope, elem, attrs, ctrl) {
scope.$watch(scope.alerts, function (newValue, oldValue) {
if(newValue === oldValue) return;
console.log("alerts is now:",scope.alerts,oldValue, newValue);
for(var i = oldValue.list.length; i < newValue.list.length; i++) {
scope.alerts.list[i].isVisible = true;
if (scope.alerts.list[i].timeout > 0) {
$timeout(function (){
scope.alerts.list[i].isVisible = false;
}, scope.alerts.list[i].timeout);
}
}
}, true);
}
}
});
if you have jQuery available, try this
if(jQuery.isEmptyObject(newValue)){
return;
}
inside scope.$watch