How to call a custom directive from angular controller - html

I have a directive which is depending on some input. I want to call that directive from angular controller when ever that input changed. Here is my directive.
var app = angular.module('App', ['ui.bootstrap']);
app.controller('fcController', function($scope, fcService, $uibModal) {
$scope.formatType = '1';
});
app.directive('fcsaNumber', function($filter) {
var addCommasToInteger, controlKeys, hasMultipleDecimals, isNotControlKey, isNotDigit, isNumber, makeIsValid, makeMaxDecimals, makeMaxDigits, makeMaxNumber, makeMinNumber;
isNumber = function(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
};
isNotDigit = function(which) {
return which < 45 || which > 57 || which === 47;
};
controlKeys = [0, 8, 13];
isNotControlKey = function(which) {
return controlKeys.indexOf(which) === -1;
};
hasMultipleDecimals = function(val) {
return (val != null) && val.toString().split('.').length > 2;
};
makeMaxDecimals = function(maxDecimals) {
var regexString, validRegex;
if (maxDecimals > 0) {
regexString = "^-?\\d*\\.?\\d{0," + maxDecimals + "}$";
} else {
regexString = "^-?\\d*$";
}
validRegex = new RegExp(regexString);
return function(val) {
return validRegex.test(val);
};
};
makeMaxNumber = function(maxNumber) {
return function(val, number) {
return number <= maxNumber;
};
};
makeMinNumber = function(minNumber) {
return function(val, number) {
return number >= minNumber;
};
};
makeMaxDigits = function(maxDigits) {
var validRegex;
validRegex = new RegExp("^-?\\d{0," + maxDigits + "}(\\.\\d*)?$");
return function(val) {
return validRegex.test(val);
};
};
makeIsValid = function(options) {
var validations;
validations = [];
if (options.maxDecimals != null) {
validations.push(makeMaxDecimals(options.maxDecimals));
}
if (options.max != null) {
validations.push(makeMaxNumber(options.max));
}
if (options.min != null) {
validations.push(makeMinNumber(options.min));
}
if (options.maxDigits != null) {
validations.push(makeMaxDigits(options.maxDigits));
}
return function(val) {
var i, number, _i, _ref;
if (!isNumber(val)) {
return false;
}
if (hasMultipleDecimals(val)) {
return false;
}
number = Number(val);
for (i = _i = 0, _ref = validations.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
if (!validations[i](val, number)) {
return false;
}
}
return true;
};
};
addCommasToInteger = function(val) {
var commas, decimals, wholeNumbers;
decimals = val.indexOf('.') == -1 ? '.00' : val.replace(/^\d+(?=\.)/, '');
wholeNumbers = val.replace(/(\.\d+)$/, '');
commas = wholeNumbers.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
return "" + commas + decimals.substring(0, 3);
};
return {
restrict: 'A',
require: 'ngModel',
scope: {
options: '#fcsaNumber',
},
link: function(scope, elem, attrs, ngModelCtrl) {
var isValid, options;
options = {};
if (scope.options != null) {
options = scope.$eval(scope.options);
}
isValid = makeIsValid(options);
ngModelCtrl.$parsers.unshift(function(viewVal) {
var noCommasVal;
noCommasVal = viewVal.replace(/,/g, '');
if (isValid(noCommasVal) || !noCommasVal) {
ngModelCtrl.$setValidity('fcsaNumber', true);
return noCommasVal;
} else {
ngModelCtrl.$setValidity('fcsaNumber', false);
return void 0;
}
});
ngModelCtrl.$formatters.push(function(val) {
if ((options.nullDisplay != null) && (!val || val === '')) {
return options.nullDisplay;
}
if ((val == null) || !isValid(val)) {
return val;
}
ngModelCtrl.$setValidity('fcsaNumber', true);
val = addCommasToInteger(val.toString());
if (options.key == 1) {
options.prepend = 'S/.';
}
if (options.key == 2) {
options.prepend = '$';
}
if (options.prepend != null) {
val = "" + options.prepend + val;
}
if (options.append != null) {
val = "" + val + options.append;
}
return val;
});
elem.on('blur', function() {
var formatter, viewValue, _i, _len, _ref;
viewValue = ngModelCtrl.$modelValue;
if ((viewValue == null) || !isValid(viewValue)) {
return;
}
_ref = ngModelCtrl.$formatters;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
formatter = _ref[_i];
viewValue = formatter(viewValue);
}
ngModelCtrl.$viewValue = viewValue;
return ngModelCtrl.$render();
});
elem.on('focus', function() {
var val;
val = elem.val();
if (options.prepend != null) {
val = val.replace(options.prepend, '');
}
if (options.append != null) {
val = val.replace(options.append, '');
}
elem.val(val.replace(/,/g, ''));
return elem[0].select();
});
if (options.preventInvalidInput === true) {
return elem.on('keypress', function(e) {
if (isNotDigit(e.which && isNotControlKey(e.which))) {
return e.preventDefault();
}
});
}
}
};
});
HTML:
<input type ="text" ng-model ="currency" fcsa-number="{key : {{formatType}}}">
Here $scope.formatType = '1'; is the input. If this formatType changed then That directive need to call. One friend suggested me this
link: function(scope,elem,attr,ctrl){
scope.$watch('fcsaNumber', function(){
// do your stuff
});
but it is not calling my directive manually.
even I have tried with
.controller("ctrl", function($scope) {
$scope.$watch('formatType', function() {
$scope.$broadcast("call_dir")
})
})
return {
restrict: 'A',
require: 'ngModel',
scope: {
options: '#fcsaNumber',
},
link: function(scope, elem, attrs, ngModelCtrl) {
var isValid, options;
options = {};
scope.$on('call_dir', function(ev) {
//your code
})
};

You need to watch the value that is going to change in your controller. In your case it is formatType.
You should try to use this expression in your isolated scope:
scope: {
options: '=fcsaNumber',
}
And if you want the event broadcasting to work, i.e. the $scope.$bradcast approach, then make sure your directive is a child of the controller scope in the scope hierarchy. Else a easier way (but not always recommended) would be to broadcast your event from $rootScope.
So something like this should also work (with your event based solution):
.controller("ctrl", function($scope, $rootScope) {
$scope.$watch('formatType', function() {
$rootScope.$broadcast("call_dir")
})
})

Related

kendoGrid and multiselectbox column initialization using query string parameters

I am implementing a custom solution that will initialize kendoGrid (and its multiselect columns) by applying filters to the grid using query string parameters. I am using Kendo UI v2014.2.903 and multiselectbox user extension.
To achieve this, I have a custom JavaScript function that parses query string parameters into filter object and applies it to kendoGrid's dataSource property using its filter method. Code snippet below:
var preFilterQueryString = getPreFilterQuery(queryString);
if (preFilterQueryString != '') {
kendoGrid.dataSource.filter(parseFilterString(preFilterQueryString));
}
I am initializing multiselectbox as follows:
args.element.kendoMultiSelectBox({
dataSource: getAutoCompleteDataSource(column.field),
valuePrimitive: true,
selectionChanged: function (e) {
//ignored for brevity
}
});
My problem is if I set filters to multiselectbox using above approach, they are not applied correctly to the data set.
For example, if I pass single filter as "Vancouver", correct result set is displayed. Choices in the multiselectbox are "All" and "Vancouver". However, Vancouver choice is not checked in the multiselectbox. Is that by design? Please see image below.
single filter image
If I pass in two filters Vancouver and Warsaw, only the last filter Warsaw is applied to the grid and data set containing only Warsaw is displayed. Again, none of the choices are checked in the multiselectbox.
two filters image
Below is the filter object that is applied to dataSource.filter() method.
kendoGrid's filter object image
Troubleshooting
Below is condensed version (for brevity) of selectionchanged event handler of a multiselectbox column.
if (e.newValue && e.newValue.length) {
var newValue = e.newValue;
console.log('e.newValue: ' + e.newValue);
filter.filters = [];
for (var i = 0, l = newValue.length; i < l; i++) {
filter.filters.push({field: field,operator: 'contains',value: newValue[i]});
}
kendoGrid.dataSource.filter(allFilters);
}
I noticed that when two filters are passed, e.newValue is "Warsaw" instead of an array - "[Vancouver, Warsaw]"
I spent lot of time troubleshooting why only Warsaw is applied to the data set.
Here's what I found out:
_raiseSelectionChanged function is what raises selection changed event. In that function, I noticed that it sets newValue and oldValue event arguments. To set newValue it uses "Value" function. Value function uses the below code to retrieve all the selected list items and return them.
else {
var selecteditems = this._getSelectedListItems();
return $.map(selecteditems, function (item) {
var obj = $(item).children("span").first();
return obj.attr("data-value");
}).join();
}
_getSelectedListItems function uses jQuery filter to fetch all list items that have css class ".selected"
_getSelectedListItems: function () {
return this._getAllValueListItems().filter("." + SELECTED);
},
There's a _select event which seems to be adding ".selected" class to list items. When I put a breakpoint on line 286, it is hitting it only once and that is for Warsaw. I am unable to understand why it is not getting called for Vancouver. I am out of clues and was wondering if anyone has pointers.
debug capture of _select function
Below is kendoMultiSelectBox user extension for your reference:
//MultiSelect - A user extension of KendoUI DropDownList widget.
(function ($) {
// shorten references to variables
var kendo = window.kendo,
ui = kendo.ui,
DropDownList = ui.DropDownList,
keys = kendo.keys,
SELECT = "select",
SELECTIONCHANGED = "selectionChanged",
SELECTED = "k-state-selected",
HIGHLIGHTED = "k-state-active",
CHECKBOX = "custom-multiselect-check-item",
SELECTALLITEM = "custom-multiselect-selectAll-item",
MULTISELECTPOPUP = "custom-multiselect-popup",
EMPTYSELECTION = "custom-multiselect-summary-empty";
var lineTemplate = '<input type="checkbox" name="#= {1} #" value="#= {0} #" class="' + CHECKBOX + '" />' +
'<span data-value="#= {0} #">#= {1} #</span>';
var MultiSelectBox = DropDownList.extend({
init: function (element, options) {
options.template = kendo.template(kendo.format(lineTemplate, options.dataValueField || 'data', options.dataTextField || 'data'));
// base call to widget initialization
DropDownList.fn.init.call(this, element, options);
var button = $('<input type="button" value="OK" style="float: right; padding: 3px; margin: 5px; cursor: pointer;" />');
button.on('click', $.proxy(this.close, this));
var popup = $(this.popup.element);
popup.append(button);
},
options: {
name: "MultiSelectBox",
index: -1,
showSelectAll: true,
preSummaryCount: 1, // number of items to show before summarising
emptySelectionLabel: '', // what to show when no items are selected
selectionChanged: null // provide callback to invoke when selection has changed
},
events: [
SELECTIONCHANGED
],
refresh: function () {
// base call
DropDownList.fn.refresh.call(this);
this._updateSummary();
$(this.popup.element).addClass(MULTISELECTPOPUP);
},
current: function (candidate) {
return this._current;
},
open: function () {
var self = this;
this._removeSelectAllItem();
this._addSelectAllItem();
if ($(this.ul).find('li').length > 6) {
$(this.popup.element).css({ 'padding-bottom': '30px' });
}
else {
$(this.popup.element).css({ 'padding-bottom': '0' });
}
DropDownList.fn.open.call(this);
//hook on to popup event because dropdown close does not
//fire consistently when user clicks on some other elements
//like a dataviz chart graphic
this.popup.one('close', $.proxy(this._onPopupClosed, this));
},
_onPopupClosed: function () {
this._removeSelectAllItem();
this._current = null;
this._raiseSelectionChanged();
},
_raiseSelectionChanged: function () {
var currentValue = this.value();
var currentValues = $.map((currentValue.length > 0 ? currentValue.split(",") : []).sort(), function (item) { return item.toString(); });
var oldValues = $.map((this._oldValue || []).sort(), function (item) { return item ? item.toString() : ''; });
// store for next pass
this._oldValue = $.map(currentValues, function (item) { return item.toString(); });
var changedArgs = { newValue: currentValues, oldValue: oldValues };
if (oldValues) {
var hasChanged = ($(oldValues).not(currentValues).length == 0 && $(currentValues).not(oldValues).length == 0) !== true;
if (hasChanged) {
//if (this.options.selectionChanged)
// this.options.selectionChanged(changedArgs);
this.trigger(SELECTIONCHANGED, changedArgs);
}
}
else if (currentValue.length > 0) {
//if (this.options.selectionChanged)
// this.options.selectionChanged(changedArgs);
this.trigger(SELECTIONCHANGED, changedArgs);
}
},
_addSelectAllItem: function () {
if (!this.options.showSelectAll) return;
var firstListItem = this.ul.children('li:first');
if (firstListItem.length > 0) {
this.selectAllListItem = $('<li tabindex="-1" role="option" unselectable="on" class="k-item ' + SELECTALLITEM + '"></li>').insertBefore(firstListItem);
// fake a data object to use for the template binding below
var selectAllData = {};
selectAllData[this.options.dataValueField || 'data'] = '*';
selectAllData[this.options.dataTextField || 'data'] = 'All';
this.selectAllListItem.html(this.options.template(selectAllData));
this._updateSelectAllItem();
this._makeUnselectable(); // required for IE8
}
},
_removeSelectAllItem: function () {
if (this.selectAllListItem) {
this.selectAllListItem.remove();
}
this.selectAllListItem = null;
},
_focus: function (li) {
if (this.popup.visible() && li && this.trigger(SELECT, { item: li })) {
this.close();
return;
}
this.select(li);
},
_keydown: function (e) {
// currently ignore Home and End keys
// can be added later
if (e.keyCode == kendo.keys.HOME ||
e.keyCode == kendo.keys.END) {
e.preventDefault();
return;
}
DropDownList.fn._keydown.call(this, e);
},
_keypress: function (e) {
// disable existing function
},
_move: function (e) {
var that = this,
key = e.keyCode,
ul = that.ul[0],
down = key === keys.DOWN,
pressed;
if (key === keys.UP || down) {
if (down) {
if (!that.popup.visible()) {
that.toggle(down);
}
if (!that._current) {
that._current = ul.firstChild;
} else {
that._current = ($(that._current)[0].nextSibling || that._current);
}
} else {
//up
// only if anything is highlighted
if (that._current) {
that._current = ($(that._current)[0].previousSibling || ul.firstChild);
}
}
if (that._current) {
that._scroll(that._current);
}
that._highlightCurrent();
e.preventDefault();
pressed = true;
} else {
pressed = DropDownList.fn._move.call(this, e);
}
return pressed;
},
selectAll: function () {
var unselectedItems = this._getUnselectedListItems();
this._selectItems(unselectedItems);
// todo: raise custom event
},
unselectAll: function () {
var selectedItems = this._getSelectedListItems();
this._selectItems(selectedItems); // will invert the selection
// todo: raise custom event
},
_selectItems: function (listItems) {
var that = this;
$.each(listItems, function (i, item) {
var idx = ui.List.inArray(item, that.ul[0]);
that.select(idx); // select OR unselect
});
},
_selectItem: function () {
// method override to prevent default selection of first item, done by normal dropdown
var that = this,
options = that.options,
useOptionIndex,
value;
useOptionIndex = that._isSelect && !that._initial && !options.value && options.index && !that._bound;
if (!useOptionIndex) {
value = that._selectedValue || options.value || that._accessor();
}
if (value) {
that.value(value);
} else if (that._bound === undefined) {
that.select(options.index);
}
},
_select: function (li) {
var that = this,
value,
text,
idx;
li = that._get(li);
if (li && li[0]) {
idx = ui.List.inArray(li[0], that.ul[0]);
if (idx > -1) {
if (li.hasClass(SELECTED)) {
li.removeClass(SELECTED);
that._uncheckItem(li);
if (this.selectAllListItem && li[0] === this.selectAllListItem[0]) {
this.unselectAll();
}
} else {
li.addClass(SELECTED);
that._checkItem(li);
if (this.selectAllListItem && li[0] === this.selectAllListItem[0]) {
this.selectAll();
}
}
if (this._open) {
that._current(li);
that._highlightCurrent();
}
var selecteditems = this._getSelectedListItems();
value = [];
text = [];
$.each(selecteditems, function (indx, item) {
var obj = $(item).children("span").first();
value.push(obj.attr("data-value"));
text.push(obj.text());
});
that._updateSummary(text);
that._updateSelectAllItem();
that._accessor(value, idx);
// todo: raise change event (add support for selectedIndex) if required
that._raiseSelectionChanged();
}
}
},
_getAllValueListItems: function () {
if (this.selectAllListItem) {
return this.ul.children("li").not(this.selectAllListItem[0]);
} else {
return this.ul.children("li");
}
},
_getSelectedListItems: function () {
return this._getAllValueListItems().filter("." + SELECTED);
},
_getUnselectedListItems: function () {
return this._getAllValueListItems().filter(":not(." + SELECTED + ")");
},
_getSelectedItemsText: function () {
var text = [];
var selecteditems = this._getSelectedListItems();
$.each(selecteditems, function (indx, item) {
var obj = $(item).children("span").first();
text.push(obj.text());
});
return text;
},
_updateSelectAllItem: function () {
if (!this.selectAllListItem) return;
// are all items selected?
if (this._getAllValueListItems().length == this._getSelectedListItems().length) {
this._checkItem(this.selectAllListItem);
this.selectAllListItem.addClass(SELECTED);
}
else {
this._uncheckItem(this.selectAllListItem);
this.selectAllListItem.removeClass(SELECTED);
}
},
_updateSummary: function (itemsText) {
if (!itemsText) {
itemsText = this._getSelectedItemsText();
}
if (itemsText.length == 0) {
this._inputWrapper.addClass(EMPTYSELECTION);
this.text(this.options.emptySelectionLabel);
return;
} else {
this._inputWrapper.removeClass(EMPTYSELECTION);
}
if (itemsText.length <= this.options.preSummaryCount) {
this._textAccessor(itemsText.join(", "));
}
else {
this._textAccessor(itemsText.length + ' selected');
}
},
_checkItem: function (itemContainer) {
if (!itemContainer) return;
itemContainer.children("input").prop("checked", true);
},
_uncheckItem: function (itemContainer) {
if (!itemContainer) return;
itemContainer.children("input").removeAttr("checked");
},
_isItemChecked: function (itemContainer) {
return itemContainer.children("input:checked").length > 0;
},
value: function (value) {
if(value != undefined)
console.log("value", value);
var that = this,
idx,
valuesList = [];
if (value !== undefined) {
if (!$.isArray(value)) {
valuesList.push(value);
this._oldValue = valuesList; // to allow for selectionChanged event
}
else {
valuesList = value;
this._oldValue = value; // to allow for selectionChanged event
}
// clear all selections first
$(that.ul[0]).children("li").removeClass(SELECTED);
$("input", that.ul[0]).removeAttr("checked");
$.each(valuesList, function (indx, item) {
var hasValue;
if (item !== null) {
item = item.toString();
}
that._selectedValue = item;
hasValue = value || (that.options.optionLabel && !that.element[0].disabled && value === "");
if (hasValue && that._fetchItems(value)) {
return;
}
idx = that._index(item);
if (idx > -1) {
that.select(
that.options.showSelectAll ? idx + 1 : idx
);
}
});
that._updateSummary();
}
else {
var selecteditems = this._getSelectedListItems();
return $.map(selecteditems, function (item) {
var obj = $(item).children("span").first();
return obj.attr("data-value");
}).join();
}
},
});
ui.plugin(MultiSelectBox);
})(jQuery);
UPDATE
I came across documentation for multiselectbox's select event that clearly states that the select event is not fired when an item is selected programmatically. Is it relevant to what I am trying to do? But why is it firing for one of the filters even though I am setting them programmatically?
enter link description here

Not able to get ng-bind-html to work

Problem: I am trying to use ng-bind-html but I am getting the following errors on the console:
The following is the controller where I am calling ngSanitize:
and using the following file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
In my form, I do the following to use ng-bind-html. So when I try to see my results, it is still rendering the &rather then &:
<div ng-bind-html="e.Specialty"></div>
and the following is what occurs in the Specialty:
Any help would be appreciated.
#lealceldeiro: Here is the controller in which I am trying to implement your suggestion but not sure where I will add it:
(
function(){
var $scope, $location;
var indexApp = angular.module('indexApp',['ui.bootstrap', 'ngSanitize']);
indexApp.controller('IndexController',function($scope,$sce,$http,$location,anchorSmoothScroll){
$scope.Lang = 'initVal';
$scope.ShowResults = false;
$scope.ShowDesc = true;
$scope.NoResults = false;
$scope.currentPage = 1;
$scope.maxPageNumbersToShow = 10;
$scope.formModel = {};
$scope.searchMode = 0;
$scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }];
$scope.Specialties = [{'value':'Family practice'},{'value':'General practice'},{'value':'Internal medicine'},{'value':'Pediatrics'}];
$scope.Gender = [{'value':'Male'},{'value':'Female'}];
$scope.Languages = {};
$scope.Cities = {};
//$scope.lastAction = '';
$scope.searchParam = {};
$("input").removeAttr('disabled');
$scope.searchParam.Distance = $scope.miles[0];
$scope.GetCurrentZip = function (){
try{
var lon, lat;
// console.log('starting geoposition code.');
if("geolocation" in navigator){
window.navigator.geolocation.getCurrentPosition(function(pos){
lat = pos.coords.latitude.toFixed(3);
lon = pos.coords.longitude.toFixed(3);
// console.log(lat + ' ' + lon);
$http.get("/Brokers-en-us/includes/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon)
.then(function(response){
$scope.searchParam.Zip = response.data;
})
})
}
else{ console.log('No geolocation'); }
}
catch(err) { console.log(err.message); }
}
$scope.GetCityList = function (){
try{
$http.get("/Brokers-en-us/includes/remote/ReturnCityList.cfm")
.then(function(response){
$scope.Cities = response.data.Cities;
})
}
catch(err){}
}
$scope.GetLangList = function (){
try{
$http.get("/Brokers-en-us/includes/remote/ReturnLangList.cfm")
.then(function(response){
$scope.Languages = response.data.Languages;
})
}
catch(err){}
}
$scope.SearchProvider = function(searchParam){
try{
//debugger;
$scope.searchMode = 1;
var queryString='';
if($scope.formModel && $scope.formModel !== searchParam){
$scope.resultsCount = 0;
currentPage = 1;
}
if(searchParam){
//debugger;
$scope.formModel = searchParam;
for(var param in searchParam){
if(searchParam.hasOwnProperty(param)){
var paramValue = searchParam[param].value ? searchParam[param].value : searchParam[param];
if (paramValue.length > 0)
queryString += param + '=' + paramValue + '&';
}
}
}
console.log(queryString);
queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;
$http.get("/Brokers-en-us/includes/remote/ReturnProvidersList.cfm" + queryString)
.then(function(response){
$scope.providers = response.data.provider;
$scope.resultsCount = response.data.rowCount;
if (!$scope.providers){
$scope.NoResults = true;
$scope.ShowResults = false;
$scope.ShowDesc = false;
}
else{
$scope.NoResults = false;
$scope.ShowResults = true;
$scope.ShowDesc = false;
}
})
}
catch(err){ alert('No response.: ' + err.message); }
}
/*Testing purposes*/
$scope.clearTopForm = function(searchParam){
//console.log("I clicked this.")
}
/*Clears the drop downs and input fields*/
$scope.$watch('searchParam.Distance', function(newValue, oldValue) {
//debugger;
if(newValue != ''){
//$scope.lastAction = 'miles';
$scope.searchParam.City = '';
$scope.searchParam.Specialty = '';
$scope.searchParam.Gender = '';
}
});
$scope.$watch('searchParam.Zip', function(newValue, oldValue) {
if(newValue != ''){
//$scope.lastAction = 'miles';
$scope.searchParam.Gender = '';
$scope.searchParam.Specialty = '';
$scope.searchParam.City = '';
}
});
$scope.cityChange = function(){
//debugger;
if($scope.searchParam.City != ''){
//$scope.lastAction = 'city';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.specialtyChange = function(){
//debugger;
if($scope.searchParam.Specialty != ''){
//$scope.lastAction = 'specialty';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.genderChange = function(){
//debugger;
if($scope.searchParam.Gender != ''){
//$scope.lastAction = 'gender';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.$watchGroup(['currentPage'], function(){
try{
if($scope.searchMode == 1){
$scope.SearchProvider($scope.formModel);
}
}
catch(err){}
});
$scope.GetCityList();
$scope.GetLangList();
$scope.GetCurrentZip();
$scope.gotoElement = function (eID){
//http://jsfiddle.net/brettdewoody/y65G5/
// set the location.hash to the id of
// the element you wish to scroll to.
//$location.hash('bottom');
// call $anchorScroll()
var browserWidth = screen.availWidth;
if (browserWidth < 768)
anchorSmoothScroll.scrollTo(eID);
};
});
indexApp.service('anchorSmoothScroll', function(){
this.scrollTo = function(eID) {
// This scrolling function
// is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
};
});
indexApp.directive('allowPattern',[allowPatternDirective]);
indexApp.directive('popPopup',[describePopup]);
indexApp.directive('pop', function pop ($tooltip, $timeout) {
var tooltip = $tooltip('pop', 'pop', 'event');
var compile = angular.copy(tooltip.compile);
tooltip.compile = function (element, attrs) {
var first = true;
attrs.$observe('popShow', function (val) {
if (JSON.parse(!first || val || false)) {
$timeout(function(){
element.triggerHandler('event');
});
}
first = false;
});
return compile(element, attrs);
};
return tooltip;
});
indexApp.filter('PhoneNumber', function(){
return function(phoneNumber){
var dash = '-';
var openParen = '(';
var closeParen = ') ';
if(phoneNumber){
var pn = phoneNumber;
pn = [pn.slice(0, 6), dash, pn.slice(6)].join('');
pn = openParen + [pn.slice(0, 3), closeParen, pn.slice(3)].join('');
return pn;
}
return phoneNumber;
}
});
indexApp.filter('Zip', function(){
return function(zipcode){
var dash = '-';
if(zipcode && zipcode.length > 5){
var zc = zipcode;
zc = [zc.slice(0, 5), dash, zc.slice(5)].join('');
return zc;
}
return zipcode;
}
});
function allowPatternDirective(){
return{
restrict: "A",
compile: function(tElement, tAttrs){
return function(scope, element, attrs){
element.bind("keypress", function(event){
var keyCode = event.which || event.keyCode;
var keyCodeChar = String.fromCharCode(keyCode);
if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){
event.preventDefault();
return false;
}
});
}
}
}
}
function describePopup(){
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover.html'
};
}
})();
(function($) {
// #todo Document this.
$.extend($,{ placeholder: {
browser_supported: function() {
return this._supported !== undefined ?
this._supported :
( this._supported = !!('placeholder' in $('<input type="text">')[0]) );
},
shim: function(opts) {
var config = {
color: '#888',
cls: 'placeholder',
selector: 'input[placeholder], textarea[placeholder]'
};
$.extend(config,opts);
return !this.browser_supported() && $(config.selector)._placeholder_shim(config);
}
}});
$.extend($.fn,{
_placeholder_shim: function(config) {
function calcPositionCss(target)
{
var op = $(target).offsetParent().offset();
var ot = $(target).offset();
return {
top: ot.top - op.top,
left: ot.left - op.left,
width: $(target).width()
};
}
function adjustToResizing(label) {
var $target = label.data('target');
if(typeof $target !== "undefined") {
label.css(calcPositionCss($target));
$(window).one("resize", function () { adjustToResizing(label); });
}
}
return this.each(function() {
var $this = $(this);
if( $this.is(':visible') ) {
if( $this.data('placeholder') ) {
var $ol = $this.data('placeholder');
$ol.css(calcPositionCss($this));
return true;
}
var possible_line_height = {};
if( !$this.is('textarea') && $this.css('height') != 'auto') {
possible_line_height = { lineHeight: $this.css('height'), whiteSpace: 'nowrap' };
}
var isBorderBox = ($this.css('box-sizing') === 'border-box');
var isTextarea = $this.is('textarea');
var ol = $('<label />')
.text($this.attr('placeholder'))
.addClass(config.cls)
.css($.extend({
position:'absolute',
display: 'inline',
'float':'none',
overflow:'hidden',
textAlign: 'left',
color: config.color,
cursor: 'text',
paddingTop: !isTextarea && isBorderBox ? '0' : $this.css('padding-top'),
paddingRight: $this.css('padding-right'),
paddingBottom: !isTextarea && isBorderBox ? '0' : $this.css('padding-bottom'),
paddingLeft: $this.css('padding-left'),
fontSize: $this.css('font-size'),
fontFamily: $this.css('font-family'),
fontStyle: $this.css('font-style'),
fontWeight: $this.css('font-weight'),
textTransform: $this.css('text-transform'),
backgroundColor: 'transparent',
zIndex: 99,
}, possible_line_height))
.css(calcPositionCss(this))
.attr('for', this.id)
.data('target',$this)
.click(function(){
if (!$(this).data('target').is(':disabled')) {
$(this).data('target').focus();
}
})
.insertBefore(this);
$this
.data('placeholder', ol)
.on('keydown', function () {
ol.hide();
})
.on('blur change', function () {
ol[$this.val().length ? 'hide' : 'show']();
})
.triggerHandler('blur');
$(window).one("resize", function () { adjustToResizing(ol); });
}
});
}
});
})(jQuery);
jQuery(document).add(window).bind('ready load', function() {
if (jQuery.placeholder) {
jQuery.placeholder.shim();
}
});
When you use ng-bind-html, AngularJS sometimes consider some contents as unsafe (as your case), so you need to use the $sce service in order to "mark" this content as safe (to be used) like this:
$sce.trustAsHtml("CLINICAL & SOCIAL"); (See demo below)
From $sanitize
The input is sanitized by parsing the HTML into tokens. All safe
tokens (from a whitelist) are then serialized back to properly escaped
html string. This means that no unsafe input can make it into the
returned string.
In this case the "unsafe" part is &
angular
.module('app', [])
.controller('ctrl', ctrl);
function ctrl($scope, $sce) {
$scope.Specialty = $sce.trustAsHtml("CLINICAL & SOCIAL");
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
<div ng-app="app" ng-controller="ctrl">
Specialty: <span ng-bind-html="Specialty"></span>
</div>

How to angular $watch element height after class change by model?

I've read and tried probably every thread on angular $watch() DOM element height but can't work out how to do this. Any help is greatly appreciated!
I have an angular app that does a simple class name update by changing a model value. Example:
class="theme-{{themeName}}"
When the class updates the DIV changes height.
I want to receive a callback on the height change.
I've tried to use $watch() and $watch(..,,true) and using both angular.element() as well as jquery ( $('foo')... ) but the $digest cycle never even calls the $watch expression.
Update (code example):
'use strict';
angular.module('k2')
.directive('k2', ['$rootScope', '$templateCache', '$timeout', 'lodash' ,'k2i',
function ($rootScope, $templateCache, $timeout, lodash, k2i) {
return {
restrict: 'E',
template: $templateCache.get('k2/templates/k2.tpl.html'),
replace: true,
scope: {
ngShow: '=',
ngHide: '=',
settings: '='
},
link: function(scope, elem, attrs) {
k2i.initK2(scope, scope.settings || {});
scope.$watch(function() {
return $('.k2 .k2-template [k2-name]').height();
}, function(newValue, oldValue, scope) {
respondToChange(newValue, oldValue, scope);
}, true);
scope.$watch(function() {
var kb = document.querySelectorAll('.k2 .k2-template [k2-name]')[0];
var ab = document.querySelectorAll('.k2 .k2-template [k2-name] .k2-acc-bar')[0];
var value = {
kb: 0,
ab: 0
}
if (kb) {
value.kb = kb.clientHeight;
}
if (ab) {
value.ab = ab.clientHeight;
}
return value;
}, function(newValue, oldValue, scope) {
respondToChange(newValue, oldValue, scope);
}, true);
function respondToChange(newValue, oldValue, scope) {
if (newValue === oldValue) return;
if (!scope.k2Pending) return;
var kbNode = document.querySelectorAll('.k2 .k2-template [k2-name="' + scope.k2Pending.name + '"]');
var abNode = document.querySelectorAll('.k2 .k2-template [k2-name="' + scope.k2Pending.name + '"] .k2-acc-bar');
// Ensure required keyboard elements are in the DOM and have height.
if ((kbNode.length > 0 && !scope.k2Pending.requiresAccessoryBar ||
kbNode.length > 0 && abNode.length > 0 && scope.k2Pending.requiresAccessoryBar) &&
(kbNode[0].clientHeight > 0 && !scope.k2Pending.requiresAccessoryBar ||
kbNode[0].clientHeight > 0 && abNode[0].clientHeight > 0 && scope.k2Pending.requiresAccessoryBar)) {
$rootScope.$emit('K2KeyboardInDOM', scope.k2Pending.name, getHeight());
}
};
function getHeight() {
var height = {};
var kbElem = angular.element(document.querySelectorAll('.k2')[0]);
var wasHidden = kbElem.hasClass('ng-hide');
kbElem.removeClass('ng-hide');
height[k2i.modes.NONE] = 0;
height[k2i.modes.ALL] = document.querySelectorAll('.k2 .k2-template [k2-name="' + scope.k2Name + '"]')[0].clientHeight;
height[k2i.modes.ACCESSORY_BAR_ONLY] = document.querySelectorAll('.k2 .k2-template [k2-name="' + scope.k2Name + '"] .k2-acc-bar')[0].clientHeight;
height[k2i.modes.KEYBOARD_KEYS_ONLY] = height[k2i.modes.ALL] - height[k2i.modes.ACCESSORY_BAR_ONLY];
if (wasHidden) {
kbElem.addClass('ng-hide');
}
return height;
};
}
}
}
]);
You should simply watch the 'themeName' variable. Then do your calculations in $timeout. $timeout should be required to wait your manual DOM updates. For ex:
scope.$watch('k2Name', function(newValue, oldValue){
$timeout(function(){
//do what you want
});
});

Changing the coordinates on Googlemaps in a template

I've found a template I really like which features a map at the bottom of the page. The attached JS file is huge and I can't see how to edit the position of the map.
There is too much code to fit in the body limit: so I have entered it into a jsfiddle: https://jsfiddle.net/5kbwkp0h/
And here is the template I'm using: https://www.freshdesignweb.com/demo/template/ubusina/
(function(root, factory) {
if(typeof exports === 'object') {
module.exports = factory();
}
else if(typeof define === 'function' && define.amd) {
define('GMaps', [], factory);
}
root.GMaps = factory();
}(this, function() {
/*!
* GMaps.js v0.4.16
* http://hpneo.github.com/gmaps/
*
* Copyright 2014, Gustavo Leon
* Released under the MIT License.
*/
if (!(typeof window.google === 'object' && window.google.maps)) {
throw 'Google Maps API is required. Please register the following JavaScript library http://maps.google.com/maps/api/js?sensor=true.'
}
var extend_object = function(obj, new_obj) {
var name;
if (obj === new_obj) {
return obj;
}
for (name in new_obj) {
obj[name] = new_obj[name];
}
return obj;
};
var replace_object = function(obj, replace) {
var name;
if (obj === replace) {
return obj;
}
for (name in replace) {
if (obj[name] != undefined) {
obj[name] = replace[name];
}
}
return obj;
};
var array_map = function(array, callback) {
var original_callback_params = Array.prototype.slice.call(arguments, 2),
array_return = [],
array_length = array.length,
i;
if (Array.prototype.map && array.map === Array.prototype.map) {
array_return = Array.prototype.map.call(array, function(item) {
callback_params = original_callback_params;
callback_params.splice(0, 0, item);
return callback.apply(this, callback_params);
});
}
else {
for (i = 0; i < array_length; i++) {
callback_params = original_callback_params;
callback_params.splice(0, 0, array[i]);
array_return.push(callback.apply(this, callback_params));
}
}
return array_return;
};
var array_flat = function(array) {
var new_array = [],
i;
for (i = 0; i < array.length; i++) {
new_array = new_array.concat(array[i]);
}
return new_array;
};
var coordsToLatLngs = function(coords, useGeoJSON) {
var first_coord = coords[0],
second_coord = coords[1];
if (useGeoJSON) {
first_coord = coords[1];
second_coord = coords[0];
}
return new google.maps.LatLng(first_coord, second_coord);
};
var arrayToLatLng = function(coords, useGeoJSON) {
var i;
for (i = 0; i < coords.length; i++) {
if (!(coords[i] instanceof google.maps.LatLng)) {
if (coords[i].length > 0 && typeof(coords[i][0]) == "object") {
coords[i] = arrayToLatLng(coords[i], useGeoJSON);
}
else {
coords[i] = coordsToLatLngs(coords[i], useGeoJSON);
}
}
}
return coords;
};
var getElementById = function(id, context) {
var element,
id = id.replace('#', '');
if ('jQuery' in this && context) {
element = $("#" + id, context)[0];
} else {
element = document.getElementById(id);
};
return element;
};
var findAbsolutePosition = function(obj) {
var curleft = 0,
curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return [curleft, curtop];
};
var GMaps = (function(global) {
"use strict";
var doc = document;
var GMaps = function(options) {
if (!this) return new GMaps(options);
options.zoom = options.zoom || 15;
options.mapType = options.mapType || 'roadmap';
var self = this,
i,
events_that_hide_context_menu = ['bounds_changed', 'center_changed', 'click', 'dblclick', 'drag', 'dragend', 'dragstart', 'idle', 'maptypeid_changed', 'projection_changed', 'resize', 'tilesloaded', 'zoom_changed'],
events_that_doesnt_hide_context_menu = ['mousemove', 'mouseout', 'mouseover'],
options_to_be_deleted = ['el', 'lat', 'lng', 'mapType', 'width', 'height', 'markerClusterer', 'enableNewStyle'],
container_id = options.el || options.div,
markerClustererFunction = options.markerClusterer,
mapType = google.maps.MapTypeId[options.mapType.toUpperCase()],
map_center = new google.maps.LatLng(options.lat, options.lng),
zoomControl = options.zoomControl || false,
zoomControlOpt = options.zoomControlOpt || {
style: 'DEFAULT',
position: 'TOP_LEFT'
},
zoomControlStyle = zoomControlOpt.style || 'DEFAULT',
zoomControlPosition = zoomControlOpt.position || 'TOP_LEFT',
panControl = options.panControl || false,
mapTypeControl = options.mapTypeControl || false,
scaleControl = options.scaleControl || true,
streetViewControl = options.streetViewControl || false,
overviewMapControl = overviewMapControl || true,
map_options = {},
map_base_options = {
zoom: this.zoom,
center: map_center,
mapTypeId: mapType
},
map_controls_options = {
panControl: panControl,
zoomControl: zoomControl,
zoomControlOptions: {
style: google.maps.ZoomControlStyle[zoomControlStyle],
position: google.maps.ControlPosition[zoomControlPosition]
},
mapTypeControl: mapTypeControl,
scaleControl: scaleControl,
streetViewControl: streetViewControl,
overviewMapControl: overviewMapControl
};
if (typeof(options.el) === 'string' || typeof(options.div) === 'string') {
this.el = getElementById(container_id, options.context);
} else {
this.el = container_id;
}
if (typeof(this.el) === 'undefined' || this.el === null) {
throw 'No element defined.';
}
window.context_menu = window.context_menu || {};
window.context_menu[self.el.id] = {};
this.controls = [];
this.overlays = [];
this.layers = []; // array with kml/georss and fusiontables layers, can be as many
this.singleLayers = {}; // object with the other layers, only one per layer
this.markers = [];
this.polylines = [];
this.routes = [];
this.polygons = [];
this.infoWindow = null;
this.overlay_el = null;
this.zoom = options.zoom;
this.registered_events = {};
this.el.style.width = options.width || this.el.scrollWidth || this.el.offsetWidth;
this.el.style.height = options.height || this.el.scrollHeight || this.el.offsetHeight;
google.maps.visualRefresh = options.enableNewStyle;
for (i = 0; i < options_to_be_deleted.length; i++) {
delete options[options_to_be_deleted[i]];
}
if(options.disableDefaultUI != true) {
map_base_options = extend_object(map_base_options, map_controls_options);
}
map_options = extend_object(map_base_options, options);
for (i = 0; i < events_that_hide_context_menu.length; i++) {
delete map_options[events_that_hide_context_menu[i]];
}
for (i = 0; i < events_that_doesnt_hide_context_menu.length; i++) {
delete map_options[events_that_doesnt_hide_context_menu[i]];
}
this.map = new google.maps.Map(this.el, map_options);
if (markerClustererFunction) {
this.markerClusterer = markerClustererFunction.apply(this, [this.map]);
}
var buildContextMenuHTML = function(control, e) {
var html = '',
options = window.context_menu[self.el.id][control];
for (var i in options){
if (options.hasOwnProperty(i)) {
var option = options[i];
html += '<li><a id="' + control + '_' + i + '" href="#">' + option.title + '</a></li>';
}
}
if (!getElementById('gmaps_context_menu')) return;
var context_menu_element = getElementById('gmaps_context_menu');
context_menu_element.innerHTML = html;
var context_menu_items = context_menu_element.getElementsByTagName('a'),
context_menu_items_count = context_menu_items.length,
i;
for (i = 0; i < context_menu_items_count; i++) {
var context_menu_item = context_menu_items[i];
var assign_menu_item_action = function(ev){
ev.preventDefault();
options[this.id.replace(control + '_', '')].action.apply(self, [e]);
self.hideContextMenu();
};
google.maps.event.clearListeners(context_menu_item, 'click');
google.maps.event.addDomListenerOnce(context_menu_item, 'click', assign_menu_item_action, false);
}
var position = findAbsolutePosition.apply(this, [self.el]),
left = position[0] + e.pixel.x - 15,
top = position[1] + e.pixel.y- 15;
context_menu_element.style.left = left + "px";
context_menu_element.style.top = top + "px";
context_menu_element.style.display = 'block';
};
this.buildContextMenu = function(control, e) {
if (control === 'marker') {
e.pixel = {};
var overlay = new google.maps.OverlayView();
overlay.setMap(self.map);
overlay.draw = function() {
var projection = overlay.getProjection(),
position = e.marker.getPosition();
e.pixel = projection.fromLatLngToContainerPixel(position);
buildContextMenuHTML(control, e);
};
}
else {
buildContextMenuHTML(control, e);
}
};
this.setContextMenu = function(options) {
window.context_menu[self.el.id][options.control] = {};
var i,
ul = doc.createElement('ul');
for (i in options.options) {
if (options.options.hasOwnProperty(i)) {
var option = options.options[i];
window.context_menu[self.el.id][options.control][option.name] = {
title: option.title,
action: option.action
};
}
}
ul.id = 'gmaps_context_menu';
ul.style.display = 'none';
ul.style.position = 'absolute';
ul.style.minWidth = '100px';
ul.style.background = 'white';
ul.style.listStyle = 'none';
ul.style.padding = '8px';
ul.style.boxShadow = '2px 2px 6px #ccc';
doc.body.appendChild(ul);
var context_menu_element = getElementById('gmaps_context_menu')
google.maps.event.addDomListener(context_menu_element, 'mouseout', function(ev) {
if (!ev.relatedTarget || !this.contains(ev.relatedTarget)) {
window.setTimeout(function(){
context_menu_element.style.display = 'none';
}, 400);
}
}, false);
};
this.hideContextMenu = function() {
var context_menu_element = getElementById('gmaps_context_menu');
if (context_menu_element) {
context_menu_element.style.display = 'none';
}
};
var setupListener = function(object, name) {
google.maps.event.addListener(object, name, function(e){
if (e == undefined) {
e = this;
}
options[name].apply(this, [e]);
self.hideContextMenu();
});
};
//google.maps.event.addListener(this.map, 'idle', this.hideContextMenu);
google.maps.event.addListener(this.map, 'zoom_changed', this.hideContextMenu);
for (var ev = 0; ev < events_that_hide_context_menu.length; ev++) {
var name = events_that_hide_context_menu[ev];
if (name in options) {
setupListener(this.map, name);
}
}
for (var ev = 0; ev < events_that_doesnt_hide_context_menu.length; ev++) {
var name = events_that_doesnt_hide_context_menu[ev];
if (name in options) {
setupListener(this.map, name);
}
}
google.maps.event.addListener(this.map, 'rightclick', function(e) {
if (options.rightclick) {
options.rightclick.apply(this, [e]);
}
if(window.context_menu[self.el.id]['map'] != undefined) {
self.buildContextMenu('map', e);
}
});
this.refresh = function() {
google.maps.event.trigger(this.map, 'resize');
};
this.fitZoom = function() {
var latLngs = [],
markers_length = this.markers.length,
i;
for (i = 0; i < markers_length; i++) {
if(typeof(this.markers[i].visible) === 'boolean' && this.markers[i].visible) {
latLngs.push(this.markers[i].getPosition());
}
}
this.fitLatLngBounds(latLngs);
};
this.fitLatLngBounds = function(latLngs) {
var total = latLngs.length;
var bounds = new google.maps.LatLngBounds();
for(var i=0; i < total; i++) {
bounds.extend(latLngs[i]);
}
this.map.fitBounds(bounds);
};
this.setCenter = function(lat, lng, callback) {
this.map.panTo(new google.maps.LatLng(lat, lng));
if (callback) {
callback();
}
};
this.getElement = function() {
return this.el;
};
this.zoomIn = function(value) {
value = value || 1;
this.zoom = this.map.getZoom() + value;
this.map.setZoom(this.zoom);
};
this.zoomOut = function(value) {
value = value || 1;
this.zoom = this.map.getZoom() - value;
this.map.setZoom(this.zoom);
};
var native_methods = [],
method;
for (method in this.map) {
if (typeof(this.map[method]) == 'function' && !this[method]) {
native_methods.push(method);
}
}
for (i=0; i < native_methods.length; i++) {
(function(gmaps, scope, method_name) {
gmaps[method_name] = function(){
return scope[method_name].apply(scope, arguments);
};
})(this, this.map, native_methods[i]);
}
};
return GMaps;
})(this);
GMaps.prototype.createControl = function(options) {
var control = document.createElement('div');
control.style.cursor = 'pointer';
if (options.disableDefaultStyles !== true) {
control.style.fontFamily = 'Roboto, Arial, sans-serif';
control.style.fontSize = '11px';
control.style.boxShadow = 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px';
}
for (var option in options.style) {
control.style[option] = options.style[option];
}
if (options.id) {
control.id = options.id;
}
if (options.classes) {
control.className = options.classes;
}
if (options.content) {
if (typeof options.content === 'string') {
control.innerHTML = options.content;
}
else if (options.content instanceof HTMLElement) {
control.appendChild(options.content);
}
}
if (options.position) {
control.position = google.maps.ControlPosition[options.position.toUpperCase()];
}
for (var ev in options.events) {
(function(object, name) {
google.maps.event.addDomListener(object, name, function(){
options.events[name].apply(this, [this]);
});
})(control, ev);
}
control.index = 1;
return control;
};
GMaps.prototype.addControl = function(options) {
var control = this.createControl(options);
this.controls.push(control);
this.map.controls[control.position].push(control);
return control;
};
GMaps.prototype.removeControl = function(control) {
var position = null;
for (var i = 0; i < this.controls.length; i++) {
if (this.controls[i] == control) {
position = this.controls[i].position;
this.controls.splice(i, 1);
}
}
if (position) {
for (i = 0; i < this.map.controls.length; i++) {
var controlsForPosition = this.map.controls[control.position]
if (controlsForPosition.getAt(i) == control) {
controlsForPosition.removeAt(i);
break;
}
}
}
return control;
};
GMaps.prototype.createMarker = function(options) {
if (options.lat == undefined && options.lng == undefined && options.position == undefined) {
throw 'No latitude or longitude defined.';
}
var self = this,
details = options.details,
fences = options.fences,
outside = options.outside,
base_options = {
position: new google.maps.LatLng(options.lat, options.lng),
map: null
},
marker_options = extend_object(base_options, options);
delete marker_options.lat;
delete marker_options.lng;
delete marker_options.fences;
delete marker_options.outside;
var marker = new google.maps.Marker(marker_options);
marker.fences = fences;
if (options.infoWindow) {
marker.infoWindow = new google.maps.InfoWindow(options.infoWindow);
var info_window_events = ['closeclick', 'content_changed', 'domready', 'position_changed', 'zindex_changed'];
for (var ev = 0; ev < info_window_events.length; ev++) {
(function(object, name) {
if (options.infoWindow[name]) {
google.maps.event.addListener(object, name, function(e){
options.infoWindow[name].apply(this, [e]);
});
}
})(marker.infoWindow, info_window_events[ev]);
}
}
var marker_events = ['animation_changed', 'clickable_changed', 'cursor_changed', 'draggable_changed', 'flat_changed', 'icon_changed', 'position_changed', 'shadow_changed', 'shape_changed', 'title_changed', 'visible_changed', 'zindex_changed'];
var marker_events_with_mouse = ['dblclick', 'drag', 'dragend', 'dragstart', 'mousedown', 'mouseout', 'mouseover', 'mouseup'];
for (var ev = 0; ev < marker_events.length; ev++) {
(function(object, name) {
if (options[name]) {
google.maps.event.addListener(object, name, function(){
options[name].apply(this, [this]);
});
}
})(marker, marker_events[ev]);
}
for (var ev = 0; ev < marker_events_with_mouse.length; ev++) {
(function(map, object, name) {
if (options[name]) {
google.maps.event.addListener(object, name, function(me){
if(!me.pixel){
me.pixel = map.getProjection().fromLatLngToPoint(me.latLng)
}
options[name].apply(this, [me]);
});
}
})(this.map, marker, marker_events_with_mouse[ev]);
}
google.maps.event.addListener(marker, 'click', function() {
this.details = details;
if (options.click) {
options.click.apply(this, [this]);
}
if (marker.infoWindow) {
self.hideInfoWindows();
marker.infoWindow.open(self.map, marker);
}
});
google.maps.event.addListener(marker, 'rightclick', function(e) {
e.marker = this;
if (options.rightclick) {
options.rightclick.apply(this, [e]);
}
if (window.context_menu[self.el.id]['marker'] != undefined) {
self.buildContextMenu('marker', e);
}
});
if (marker.fences) {
google.maps.event.addListener(marker, 'dragend', function() {
self.checkMarkerGeofence(marker, function(m, f) {
outside(m, f);
});
});
}
return marker;
};
GMaps.prototype.addMarker = function(options) {
var marker;
if(options.hasOwnProperty('gm_accessors_')) {
// Native google.maps.Marker object
marker = options;
}
else {
if ((options.hasOwnProperty('lat') && options.hasOwnProperty('lng')) || options.position) {
marker = this.createMarker(options);
}
else {
throw 'No latitude or longitude defined.';
}
}
marker.setMap(this.map);
if(this.markerClusterer) {
this.markerClusterer.addMarker(marker);
}
this.markers.push(marker);
GMaps.fire('marker_added', marker, this);
return marker;
};
GMaps.prototype.addMarkers = function(array) {
for (var i = 0, marker; marker=array[i]; i++) {
this.addMarker(marker);
}
return this.markers;
};
GMaps.prototype.hideInfoWindows = function() {
for (var i = 0, marker; marker = this.markers[i]; i++){
if (marker.infoWindow) {
marker.infoWindow.close();
}
}
};
GMaps.prototype.removeMarker = function(marker) {
for (var i = 0; i < this.markers.length; i++) {
if (this.markers[i] === marker) {
this.markers[i].setMap(null);
this.markers.splice(i, 1);
if(this.markerClusterer) {
this.markerClusterer.removeMarker(marker);
}
GMaps.fire('marker_removed', marker, this);
break;
}
}
return marker;
};
GMaps.prototype.removeMarkers = function (collection) {
var new_markers = [];
if (typeof collection == 'undefined') {
for (var i = 0; i < this.markers.length; i++) {
var marker = this.markers[i];
marker.setMap(null);
if(this.markerClusterer) {
this.markerClusterer.removeMarker(marker);
}
GMaps.fire('marker_removed', marker, this);
}
this.markers = new_markers;
}
else {
for (var i = 0; i < collection.length; i++) {
var index = this.markers.indexOf(collection[i]);
if (index > -1) {
var marker = this.markers[index];
marker.setMap(null);
if(this.markerClusterer) {
this.markerClusterer.removeMarker(marker);
}
GMaps.fire('marker_removed', marker, this);
}
}
for (var i = 0; i < this.markers.length; i++) {
var marker = this.markers[i];
if (marker.getMap() != null) {
new_markers.push(marker);
}
}
this.markers = new_markers;
}
};
GMaps.prototype.drawOverlay = function(options) {
var overlay = new google.maps.OverlayView(),
auto_show = true;
overlay.setMap(this.map);
if (options.auto_show != null) {
auto_show = options.auto_show;
}
overlay.onAdd = function() {
var el = document.createElement('div');
el.style.borderStyle = "none";
el.style.borderWidth = "0px";
el.style.position = "absolute";
el.style.zIndex = 100;
el.innerHTML = options.content;
overlay.el = el;
if (!options.layer) {
options.layer = 'overlayLayer';
}
var panes = this.getPanes(),
overlayLayer = panes[options.layer],
stop_overlay_events = ['contextmenu', 'DOMMouseScroll', 'dblclick', 'mousedown'];
overlayLayer.appendChild(el);
for (var ev = 0; ev < stop_overlay_events.length; ev++) {
(function(object, name) {
google.maps.event.addDomListener(object, name, function(e){
if (navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) {
e.cancelBubble = true;
e.returnValue = false;
}
else {
e.stopPropagation();
}
});
})(el, stop_overlay_events[ev]);
}
I ran a find for this: "new GMaps({"
changed 'em, done!
thanks.

Testing directive link in angular js

I am testing following directive in angular Jasmine unit test
angular.module('components.privileges', [])
.directive('hasPrivilege', function(privileges) {
return {
link: function (scope, element, attrs, $rootScope) {
if (!angular.isString(attrs.hasPrivilege)) {
throw "hasPrivilege value must be a string";
}
function toggleVisibilityBasedOnPrivilege() {
var hasPrivilege = privileges.evaluatePrivilegeExpression(attrs.hasPrivilege.trim());
console.log(hasPrivilege);
if (hasPrivilege) {
element.show();
} else {
element.hide();
}
}
toggleVisibilityBasedOnPrivilege();
$rootScope.$on('privilegesChanged', function(event, data){
toggleVisibilityBasedOnPrivilege();
});
}
};
}).factory('privileges', function ($rootScope) {
var privilegesList = {};
return {
clearPrivileges: function () {
privilegesList = {};
},
setPrivileges: function (privileges) {
privilegesList["PRIVILEGES_SET_FLAG"] = true;
if(angular.isDefined(privileges) && angular.isArray(privileges) && privileges.length > 0){
for(var p in privileges) {
var k = privileges[p];
if( k && angular.isString(k) && k.trim()!==""){
privilegesList[privileges[p]] = true;
}
}
}
$rootScope.$emit('privilegesChanged');
},
privilegesLoaded: function () {
return angular.isDefined(privilegesList["PRIVILEGES_SET_FLAG"]);
},
hasPrivilege: function (p) {
var k = p && angular.isString(p) ? p.trim() : "";
return p === "NA" || ( k!=="" && angular.isDefined(privilegesList[k]) );
},
evaluatePrivilegeExpression: function (exp) {
var isPrivileged = false;
if( exp !== undefined && exp !== null && angular.isString(exp)){
exp = exp.trim();
if(exp !== "" && exp !== "!"){
var value = exp;
var notPrivilegeFlag = value[0] === '!';
if (notPrivilegeFlag) {
value = value.slice(1).trim();
}
var hasPrivilege = this.hasPrivilege(value);
isPrivileged = (hasPrivilege && !notPrivilegeFlag || !hasPrivilege && notPrivilegeFlag);
}
}
return isPrivileged;
}
};
});
In the directive, when i call setprivileges, I use '$rootScope.$emit('privilegesChanged');' event to notify that the privileges are changed. If, my div does not have the privilege, it must be hidden otherwise available.
And my test case is as follows:-
describe("directive: hasPrivilege: ",function(){
var element, scope, priviledgesArray, $privilegesFactory, $compile;
beforeEach(function(){
module("components.privileges");
inject(function(privileges, _$rootScope_, _$compile_) {
$privilegesFactory = privileges;
scope= _$rootScope_;
$compile = _$compile_ ;
});
priviledgesArray = ["123"];
});
it("should hide the element when privileges have not been set", function(){
element = $compile('<div has-privilege="123"></div>')(scope);
scope.$digest();
$privilegesFactory.setPrivileges(priviledgesArray);
console.log($(element).find("div"));
expect($(element).find("div").style.display).toBe("block");
});
});
});
When i ran the test case, I got following error
TypeError: 'undefined' is not a function (evaluating 'element.hide()')
I am not getting what is the issue. Can someone help?
Try referencing element as an array in the directive, i.e. element[0].show(); and element[0].hide();.