Angularjs using a factory properly - html

I was wondering if you could help.
I have the below code which sets a timeout delay before making a http request. The watch is bound to a input box. This is currently in my controller and it works.
$scope.$watch('query.keyword',function($http){
var searchInput = document.getElementById('searchInput').value;
var minLength = 3;
var req;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function(){
var newValue = searchInput;
if(newValue !== null && newValue.length > minLength) {
window.alert(newValue);
req = {
method: 'SET',
url: ''
};
}
}, 3000);
return $http(req);
});
Now I want this as a factory/service to call upon rather than listing it in my controller.
I then made this...
app.factory('sendSearchData', function($http) {
var searchInput = document.getElementById('searchInput').value;
var minLength = 3;
var req = null;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function(){
var newValue = searchInput;
if(newValue !== null && newValue.length > minLength) {
window.alert(newValue);
req = {
method: 'SET',
url: 'haha.php'
};
}
}, 3000);
return function() {
if($http !== null) {
return $http(req);
} else { return 0; }
};
});
Not sure if the return is right, as the previous return was flagging up a http null error.
So to use it I've done a few variations of the below code in my controller.
$scope.$watch('query.keyword', sendSearchData.success());
But I am having no luck and it's refusing to render.
Can anyone help?

Related

My site doesn't work after the update Chrome 83

So, I have website on ext.net 1.7 (last version), and after updates my site doesn't works. The Chrome-console shows no errors. It's just no worked. But it worked in previous versions of Chrome.
WebConsoleErrors
I read about change in Chrome but found nothing the problem.
Does anyone know what the problem is?
try this
(function () {
function isChromium() {
var isChromium = window.chrome;
var winNav = window.navigator;
var isIOSChrome = winNav.userAgent.match("CriOS");
if (isIOSChrome)
return true;
else if (isChromium !== null && typeof isChromium !== "undefined")
return true;
else
return false;
}
if (isChromium()) {
Ext.override(Ext.data.Connection, {
doFormUpload: function (o, ps, url) {
var me = this;
var doc = document;
var form = Ext.getDom(o.form);
var hiddens = [];
var hd;
Ext.iterate(Ext.urlDecode(ps, false), function (k, v) {
hd = doc.createElement('input');
Ext.fly(hd).set({
type: 'hidden',
value: v,
name: k
});
form.appendChild(hd);
hiddens.push(hd);
});
var formData = new FormData(form);
function successCallback(data) {
var r = {
responseText: '',
responseXML: null,
argument: o.argument
};
if (data) {
var match = /<textarea>(.+)<\/textarea>/i.exec(data);
if (match != null && match.length >= 2) {
r.responseText = match[1];
} else {
r.responseText = data;
}
r.responseXML = $.parseXML(data);
}
me.fireEvent("requestcomplete", me, r, o);
function runCallback(fn, scope, args) {
if (Ext.isFunction(fn)) {
fn.apply(scope, args);
}
}
runCallback(o.success, o.scope, [r, o]);
runCallback(o.callback, o.scope, [o, true, r]);
}
$.ajax({
type: 'POST',
url: url,
data: formData,
processData: false,
contentType: false,
success: successCallback,
error: function () {
console.log(arguments);
}
});
Ext.each(hiddens, function (h) {
Ext.removeNode(h);
});
}
})
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
You should insert current script in body for all pages after load extjs

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

Haxe IE9 xmlHTTPrequest issue

I'm having problems displaying my Haxe game in IE9. It's actually not displaying at all. We tracked down the issue inside the compiled JS file for Haxe and found out that the problem is within the haxe.HTTP API.
There are certain things that need to be checked and done for IE9 to work with xmlhttprequests. These things were not done in the Haxe API.
This is the http class without my fix:
this.url = url;
this.headers = new List();
this.params = new List();
this.async = true;
};
$hxClasses["haxe.Http"] = haxe.Http;
haxe.Http.__name__ = ["haxe","Http"];
haxe.Http.prototype = {
setParameter: function(param,value) {
this.params = Lambda.filter(this.params,function(p) {
return p.param != param;
});
this.params.push({ param : param, value : value});
return this;
}
,request: function(post) {
var me = this;
me.responseData = null;
var r = this.req = js.Browser.createXMLHttpRequest();
var onreadystatechange = function(_) {
if(r.readyState != 4) return;
var s;
try {
s = r.status;
} catch( e ) {
s = null;
}
if(s == undefined) s = null;
if(s != null) me.onStatus(s);
if(s != null && s >= 200 && s < 400) {
me.req = null;
me.onData(me.responseData = r.responseText);
} else if(s == null) {
me.req = null;
me.onError("Failed to connect or resolve host");
} else switch(s) {
case 12029:
me.req = null;
me.onError("Failed to connect to host");
break;
case 12007:
me.req = null;
me.onError("Unknown host");
break;
default:
me.req = null;
me.responseData = r.responseText;
me.onError("Http Error #" + r.status);
}
};
if(this.async) r.onreadystatechange = onreadystatechange;
var uri = this.postData;
if(uri != null) post = true; else {
var $it0 = this.params.iterator();
while( $it0.hasNext() ) {
var p = $it0.next();
if(uri == null) uri = ""; else uri += "&";
uri += encodeURIComponent(p.param) + "=" + encodeURIComponent(p.value);
}
}
try {
if(post) r.open("POST",this.url,this.async); else if(uri != null) {
var question = this.url.split("?").length <= 1;
r.open("GET",this.url + (question?"?":"&") + uri,this.async);
uri = null;
} else r.open("GET",this.url,this.async);
} catch( e1 ) {
me.req = null;
this.onError(e1.toString());
return;
}
if(!Lambda.exists(this.headers,function(h) {
return h.header == "Content-Type";
}) && post && this.postData == null) r.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var $it1 = this.headers.iterator();
while( $it1.hasNext() ) {
var h1 = $it1.next();
r.setRequestHeader(h1.header,h1.value);
}
r.send(uri);
if(!this.async) onreadystatechange(null);
}
,onData: function(data) {
}
,onError: function(msg) {
}
,onStatus: function(status) {
}
,__class__: haxe.Http
};
and this is the code WITH the fix:
haxe.Http = function(url) {
this.url = url;
this.headers = new List();
this.params = new List();
this.async = true;
};
$hxClasses["haxe.Http"] = haxe.Http;
haxe.Http.__name__ = ["haxe","Http"];
haxe.Http.prototype = {
setParameter: function(param,value) {
this.params = Lambda.filter(this.params,function(p) {
return p.param != param;
});
this.params.push({ param : param, value : value});
return this;
}
,request: function(post) {
var me = this;
me.responseData = null;
var r = this.req = js.Browser.createXMLHttpRequest();
var onreadystatechange = function(_) {
console.log('in onreadystatechange function');
//if(r.readyState != 4) return;
console.log(r.responseText);
console.log('r.status: ' + r.status);
me.req = null;
me.onData(me.responseData = r.responseText);
};
if(typeof XDomainRequest != "undefined") {
console.log('XDomainRequest');
r.onload = onreadystatechange;
}
var uri = this.postData;
try {
console.log('calling r.open with url: ' + this.url);
r.open("GET",this.url);
} catch( e1 ) {
me.req = null;
this.onError(e1.toString());
return;
}
//r.send(uri);
//do it, wrapped in timeout to fix ie9
setTimeout(function () {
r.send();
}, 0);
//if(!this.async) onreadystatechange(null);
}
,onData: function(data) {
}
,onError: function(msg) {
}
,onStatus: function(status) {
}
,__class__: haxe.Http
};
Note that this only implements the IE9 fix without doing the if statements to keep support for other browsers. But it's really easy. the IF statement is simply
if(typeof XDomainRequest != "undefined") return new XDomainRequest();
Basically, I know what the issue is, I just have no idea how I can change these things within the core of Haxe itself.
Thanks.
https://github.com/HaxeFoundation/haxe/pull/3449
BAM! Got it working in a local version of my haxe. Fixed for all browsers and sent a pull request. :D
Good job on this one!
You have to contact the Haxe mailing list directly, most thinking heads are over there rather than here :)
https://groups.google.com/d/forum/haxelang

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();.

AngularJS function undefined when uncommenting it

I have some weird problems related with defintion of method inside scope. Once it's defined, and when I want to call it (just by entering it into code) it disappears. I have this part of code
if (ConfigurationService.isConfigurationChanged() === true) {
ConfigurationService.getConfiguration().then(function(data) {
$scope.configuration = data.configuration;
$scope.lunchers = data.lunchers;
$scope.configuration.vegies.all_in_one_group = data.configuration.vegies.all_in_one_group;
var lunchersLength = data.lunchers.all.length;
for (var i = 0; i < lunchersLength; i++) {
$scope.selectedVegies[i] = $scope.isVegie(data.lunchers.all[i]);
$scope.selectedSpecialGroup[i] = $scope.isInSpecialGroup(data.lunchers.all[i]);
$scope.isAbsent[i] = $scope.isAbsent(data.lunchers.all[i]);
}
});
} else if (ConfigurationService.isConfigurationChanged() === false) {
var cached = ConfigurationService.getCachedConfiguration();
console.log($scope.isVegie);
$scope.configuration = cached.configuration;
$scope.lunchers = cached.lunchers;
$scope.configuration.vegies.all_in_one_group = cached.configuration.vegies.all_in_one_group;
var lunchersLength = cached.lunchers.all.length;
for (var j = 0; j < lunchersLength; j++) {
$scope.selectedVegies[i] = $scope.isVegie(cached.lunchers.all[j]);
//$scope.selectedSpecialGroup[i] = $scope.isInSpecialGroup(cached.lunchers.all[i]);
//$scope.isAbsent[i] = $scope.isAbsent(cached.lunchers.all[i]);
}
}
Now something weird happens. Can you see:
console.log($scope.isVegie);
When I have:
$scope.selectedVegies[i] = $scope.isVegie(cached.lunchers.all[j]);
commented I can see method in firebug, when I uncomment it, it gets undefined...
Anybody had some similar issues?
Note:
ConfigurationService.getConfiguration()
Is this method:
getConfiguration : function() {
var deferred = $q.defer();
$http({
method :'GET',
url : "cgi-bin/get_configuration.py"
})
.success(function(data, status, headers, config) {
if (status === 200) {
angular.copy(data, configStatus.currentConfig);// = data;
configStatus.configurationChanged = false;
deferred.resolve(data);
}
})
.error(function(data, status, headers, config) {
console.log(data);
console.log(status);
deferred.reject(data);
});
return deferred.promise;
},
Found the issue. The thing is that
$scope.isVegie
was defined after the logic calling it. However, I didn't noticed that when I didn't have else part. When it was without if-else, it was working fine even though method was defined "under" the logic calling it.
This solved the issue.