Odoo 13 : Error Js "Could not find client action" - javascript

I received the following error: Could not find client action eacta_previsionnel_hebdomadaire
XML code
<record id="eacta_previsionnel_report_action_client" model="ir.actions.client" >
<field name="name">Prévisionnel hebdomadaire</field>
<field name="tag">eacta_previsionnel_hebdomadaire</field>
</record>
JS code :
odoo.define('eacta_previsionnel.eacta_previsionnel_hebdomadaire', function (require) {
'use strict';
var core = require('web.core');
var Widget = require('web.Widget');
var ControlPanelMixin = require('web.ControlPanelMixin');
var AbstractAction = require('web.AbstractAction');
var SearchView = require('web.SearchView');
var data = require('web.data');
var pyeval = require('web.pyeval');
var field_utils = require('web.field_utils');
var session = require('web.session');
var datepicker = require('web.datepicker');
var QWeb = core.qweb;
var _t = core._t;
var ClientAction = AbstractAction.extend(ControlPanelMixin, {
custom_events: {
search: '_onSearch',
},
events:{
'change .o_eacta_date_start': 'on_change_date_start',
'change .o_mps_save_input_text': 'save_line_prevision',
'click .o_eacta_product_name': 'open_eacta_product',
'click .o_eacta_variete_name': 'open_eacta_plantation',
'click .o_eacta_next_week': 'on_click_next_week',
'click .o_eacta_prev_week': 'on_click_prev_week',
},
init: function(parent, action) {
this.actionManager = parent;
this.action = action;
this.domain = [];
return this._super.apply(this, arguments);
},
render_search_view: function(){
var self = this;
var defs = [];
this._rpc({
model: 'ir.model.data',
method: 'get_object_reference',
args: ['eacta_mrp_base', 'eacta_search_mrp_farm_plantation'],
})
.then(function(view_id){
self.dataset = new data.DataSetSearch(this, 'eacta.r.variete.serre.period');
self.loadFieldView(self.dataset, view_id[1], 'search')
.then(function (fields_view) {
self.fields_view = fields_view;
var options = {
$buttons: $("<div>"),
action: this.action,
disable_groupby: true,
};
self.searchview = new SearchView(self, self.dataset, self.fields_view, options);
self.searchview.appendTo($("<div>")).then(function () {
self.$searchview_buttons = self.searchview.$buttons.contents();
self.update_cp();
defs.push(self.update_cp());
});
});
});
},
willStart: function() {
return this.get_html();
},
start: function() {
var self = this;
this.render_search_view();
return this._super.apply(this, arguments).then(function () {
self.$el.html(self.html);
});
},
re_renderElement: function() {
this.$el.html(this.html);
this.update_cp();
},
open_eacta_product: function(e){
this.do_action({
type: 'ir.actions.act_window',
res_model: "eacta.conf.culture",
res_id: parseInt($(e.target).data('product')),
views: [[false, 'form']],
});
},
open_eacta_plantation: function(e){
this.do_action({
type: 'ir.actions.act_window',
res_model: "eacta.r.variete.serre.period",
res_id: parseInt($(e.target).data('plantation')),
views: [[false, 'form']],
});
},
save_line_prevision: function(e){
var self = this;
var $input = $(e.target);
var target_value;
try {
target_value = field_utils.parse.float($input.val().replace(String.fromCharCode(8209), '-'));
} catch(err) {
return this.do_warn(_t("Wrong value entered!"), err);
}
return this._rpc({
model: 'eacta.data.recolte.previsionnel',
method: 'save_line_prevision',
args: [field_utils.parse.float($input.val()), parseInt($input.data('plantation')),$input.data('date')],
})
.done(function(res){
self.get_html().then(function() {
self.re_renderElement();
self.update_cp();
});
});
},
on_change_date_start: function(e){
var self = this;
var $input = $(".o_eacta_date_start").val();
var target_value;
try {
if ($input == ''){
this.do_warn(_t("Wrong value entered!"), "<ul><li>Date de debut</li></ul>");
return;
}
// target_value = field_utils.format.date(field_utils.parse.date($input, {}, {isUTC: true}));
} catch(err) {
return this.do_warn(_t("Wrong value entered!"), err);
}
return this._rpc({
model: 'eacta.previsionnel.hebdomadaire',
method: 'search',
args: [[]],
})
.then(function(res){
return self._rpc({
model: 'eacta.previsionnel.hebdomadaire',
method: 'write',
args: [res, {'date_start': $input}],
})
.done(function(result){
self.get_html().then(function() {
self.re_renderElement();
self.update_cp();
});
});
});
},
on_click_next_week: function(e){
var self = this;
var date = self.operation_date("next",7);
var max_next_date = new Date(date[2], parseInt(date[1])-1,date[0])
var date_max = new Date($('.o_eacta_date_start').getAttributes()["date-max"]);
if (max_next_date > date_max)
$(".o_eacta_date_start").val(field_utils.parse.date(date_max).format('DD/MM/YYYY'));
else
$(".o_eacta_date_start").val(date[0] + "/" + date[1] + "/" + date[2]);
self.on_change_date_start();
},
on_click_prev_week: function(e){
var self = this;
var date = self.operation_date("prev",7);
var min_prev_date = new Date(date[2], parseInt(date[1])-1,date[0])
var date_min = new Date($('.o_eacta_date_start').getAttributes()["date-min"]);
if (min_prev_date < date_min)
$(".o_eacta_date_start").val(field_utils.parse.date(date_min).format('DD/MM/YYYY'));
else
$(".o_eacta_date_start").val(date[0] + "/" + date[1] + "/" + date[2]);
self.on_change_date_start();
},
operation_date: function(operation,nbr_day){
var counter = 0;
counter = counter + nbr_day;
var today = new Date($(".o_eacta_date_start").datepicker( "getDate" ));
if (operation == "next")
today.setDate(today.getDate() + counter);
else if (operation == "prev")
today.setDate(today.getDate() - counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
return [d,m,y]
},
get_html: function() {
var self = this;
return this._rpc({
model: 'eacta.previsionnel.hebdomadaire',
method: 'get_html',
args: [this.domain],
})
.then(function (result) {
self.html = result.html;
self.report_context = result.report_context;
});
},
update_cp: function() {
var self = this;
self.readonly_input_previsionnel();
self.enabled_input_previsionnel();
self.sous_total_previsionnel();
self.total_previsionnel();
self.total_sous_total_previsionnel();
self.visibility_icon_next();
self.visibility_icon_prev();
this.update_control_panel({
breadcrumbs: this.actionManager.get_breadcrumbs(),
cp_content: {
$buttons: this.$buttons,
$searchview: this.searchview.$el,
// $searchview_buttons: this.$searchview_buttons,
$searchview_buttons: this.$searchview_buttons
},
searchview: this.searchview,
});
},
total_previsionnel: function() {
$('.demand_forecast').each(function () {
var sum = 0.00
$(this).find('.text-right .o_mps_save_input_text').each(function () {
sum += Number(field_utils.parse.float($(this).context.value));
});
$(this).find('.o_mps_save_input_text_total').html(field_utils.format.float(sum));
});
},
sous_total_previsionnel: function(){
var list_periode = [];
var sum = 0.00;
$('tr.demand_forecast:first td.text-right input').each(function () {
list_periode.push($(this)[0].attributes['data-date'].value);
});
for (var i = 0;i< list_periode.length;i++){
$('.demand_forecast') .parent() .each(function () {
sum = 0.00;
$(this).find('input[data-date='+list_periode[i]+']').each(function () {
sum += field_utils.parse.float($(this).context.value);
});
$(this).parent().find('span[class=o_eacta_sous_total][data-date='+list_periode[i]+']').html(field_utils.format.float(sum));
});
}
},
total_sous_total_previsionnel: function(){
var sum = 0.00;
$('.demand_forecast').parent().parent().each(function () {
$(this).find('span[class=o_eacta_sous_total]').each(function () {
sum += field_utils.parse.float($(this).text());
});
$(this).find('tr.active td:last .o_eacta_total_sous_total').html(field_utils.format.float(sum));
sum = 0.00;
});
},
enabled_input_previsionnel: function() {
$('.demand_forecast').each(function () {
$(this).find('.eacta_readonly').each(function () {
$(this).prop('disabled', true);
$(this).prop('readonly', true);
$(this).css('background-color', 'transparent');
$(this).css('color', '#AEA79F');
});
});
},
readonly_input_previsionnel: function() {
$('.demand_forecast').each(function () {
$(this).find('.eacta_input_span_readonly').each(function () {
$(this).prop('disabled', true);
$(this).prop('readonly', true);
$(this).css('background-color', '#ffffff');
$(this).css('border', 'medium none');
});
});
},
visibility_icon_next:function(){
var self = this;
var date = self.operation_date("next",7);
var max_next_date = new Date(date[2], parseInt(date[1])-1,date[0])
var date_max = new Date($('.o_eacta_date_start').getAttributes()["date-max"]);
if (max_next_date > date_max)
$('.o_eacta_next_week').css('visibility', 'hidden');
else
$('.o_eacta_next_week').css('visibility', 'visible');
},
visibility_icon_prev:function(){
var self = this;
var date = self.operation_date("prev",7);
var min_prev_date = new Date(date[2], parseInt(date[1])-1,date[0])
var date_min = new Date($('.o_eacta_date_start').getAttributes()["date-min"]);
if (min_prev_date < date_min)
$('.o_eacta_prev_week').css('visibility', 'hidden');
else
$('.o_eacta_prev_week').css('visibility', 'visible');
},
_onSearch: function (event) {
var session = this.getSession();
var result = pyeval.eval_domains_and_contexts({
contexts: [session.user_context],
domains: event.data.domains
});
this.domain = result.domain;
this.update_cp();
this.get_html().then(this.re_renderElement.bind(this));
},
});
core.action_registry.add('eacta_previsionnel_hebdomadaire', ClientAction );
return ClientAction ;
});
I am using Odoo 13
What I am doing wrong here?
Let me know if you need more details.
thanks!

Related

Why is a function running before the others?

I have the following code I got from codepen.io to generate a calendar:
!function() {
var today = moment().locale('es');
function Calendar(selector, events) {
this.el = document.querySelector(selector);
this.events = events;
this.current = moment().date(1);
this.draw();
var current = document.querySelector('.today');
if(current) {
var self = this;
window.setTimeout(function() {
self.openDay(current);
}, 500);
}
}
Calendar.prototype.draw = function() {
//Create Header
this.drawHeader();
//Draw Month
this.drawMonth();
}
Calendar.prototype.drawHeader = function() {
var self = this;
if(!this.header) {
//Create the header elements
this.header = createElement('div', 'header');
this.header.className = 'header';
this.title = createElement('h1');
var right = createElement('div', 'right');
right.addEventListener('click', function() { self.nextMonth(); });
var left = createElement('div', 'left');
left.addEventListener('click', function() { self.prevMonth(); });
//Append the Elements
this.header.appendChild(this.title);
this.header.appendChild(right);
this.header.appendChild(left);
this.el.appendChild(this.header);
}
this.title.innerHTML = this.current.locale('es').format('MMMM YYYY');
}
Calendar.prototype.drawMonth = function() {
var self = this;
this.events.forEach(function(ev) {
ev.date = moment(ev.date);
});
if(this.month) {
this.oldMonth = this.month;
this.oldMonth.className = 'month out ' + (self.next ? 'next' : 'prev');
this.oldMonth.addEventListener('webkitAnimationEnd', function() {
self.oldMonth.parentNode.removeChild(self.oldMonth);
self.month = createElement('div', 'month');
self.backFill();
self.currentMonth();
self.fowardFill();
self.el.appendChild(self.month);
window.setTimeout(function() {
self.month.className = 'month in ' + (self.next ? 'next' : 'prev');
}, 16);
});
} else {
this.month = createElement('div', 'month');
this.el.appendChild(this.month);
this.backFill();
this.currentMonth();
this.fowardFill();
this.month.className = 'month new';
}
}
Calendar.prototype.backFill = function() {
var clone = this.current.clone();
var dayOfWeek = clone.day();
if(!dayOfWeek) { return; }
clone.subtract('days', dayOfWeek+1);
for(var i = dayOfWeek; i > 0 ; i--) {
this.drawDay(clone.add('days', 1));
}
}
Calendar.prototype.fowardFill = function() {
var clone = this.current.clone().add('months', 1).subtract('days', 1);
var dayOfWeek = clone.day();
if(dayOfWeek === 6) { return; }
for(var i = dayOfWeek; i < 6 ; i++) {
this.drawDay(clone.add('days', 1));
}
}
Calendar.prototype.currentMonth = function() {
var clone = this.current.clone();
while(clone.month() === this.current.month()) {
this.drawDay(clone);
clone.add('days', 1);
}
}
Calendar.prototype.getWeek = function(day) {
if(!this.week || day.day() === 0) {
this.week = createElement('div', 'week');
this.month.appendChild(this.week);
}
}
Calendar.prototype.drawDay = function(day) {
var self = this;
this.getWeek(day);
//Outer Day
var outer = createElement('div', this.getDayClass(day));
outer.addEventListener('click', function() {
self.openDay(this);
});
//Day Name
var name = createElement('div', 'day-name', day.locale('es').format('ddd'));
//Day Number
var number = createElement('div', 'day-number', day.format('DD'));
//Events
var events = createElement('div', 'day-events');
this.drawEvents(day, events);
outer.appendChild(name);
outer.appendChild(number);
outer.appendChild(events);
this.week.appendChild(outer);
}
Calendar.prototype.drawEvents = function(day, element) {
if(day.month() === this.current.month()) {
var todaysEvents = this.events.reduce(function(memo, ev) {
if(ev.date.isSame(day, 'day')) {
memo.push(ev);
}
return memo;
}, []);
todaysEvents.forEach(function(ev) {
var evSpan = createElement('span', ev.color);
element.appendChild(evSpan);
});
}
}
Calendar.prototype.getDayClass = function(day) {
classes = ['day'];
if(day.month() !== this.current.month()) {
classes.push('other');
} else if (today.isSame(day, 'day')) {
classes.push('today');
}
return classes.join(' ');
}
Calendar.prototype.openDay = function(el) {
var details, arrow;
var dayNumber = +el.querySelectorAll('.day-number')[0].innerText || +el.querySelectorAll('.day-number')[0].textContent;
var day = this.current.clone().date(dayNumber);
var currentOpened = document.querySelector('.details');
//Check to see if there is an open detais box on the current row
if(currentOpened && currentOpened.parentNode === el.parentNode) {
details = currentOpened;
arrow = document.querySelector('.arrow');
} else {
//Close the open events on differnt week row
//currentOpened && currentOpened.parentNode.removeChild(currentOpened);
if(currentOpened) {
currentOpened.addEventListener('webkitAnimationEnd', function() {
currentOpened.parentNode.removeChild(currentOpened);
});
currentOpened.addEventListener('oanimationend', function() {
currentOpened.parentNode.removeChild(currentOpened);
});
currentOpened.addEventListener('msAnimationEnd', function() {
currentOpened.parentNode.removeChild(currentOpened);
});
currentOpened.addEventListener('animationend', function() {
currentOpened.parentNode.removeChild(currentOpened);
});
currentOpened.className = 'details out';
}
//Create the Details Container
details = createElement('div', 'details in');
//Create the arrow
var arrow = createElement('div', 'arrow');
//Create the event wrapper
details.appendChild(arrow);
el.parentNode.appendChild(details);
}
var todaysEvents = this.events.reduce(function(memo, ev) {
if(ev.date.isSame(day, 'day')) {
memo.push(ev);
}
return memo;
}, []);
this.renderEvents(todaysEvents, details);
arrow.style.left = el.offsetLeft - el.parentNode.offsetLeft + 27 + 'px';
}
Calendar.prototype.renderEvents = function(events, ele) {
//Remove any events in the current details element
var currentWrapper = ele.querySelector('.events');
var wrapper = createElement('div', 'events in' + (currentWrapper ? ' new' : ''));
events.forEach(function(ev) {
var div = createElement('div', 'event');
var square = createElement('div', 'event-category ' + ev.color);
var span = createElement('span', '', ev.eventName);
div.appendChild(square);
div.appendChild(span);
wrapper.appendChild(div);
});
if(!events.length) {
var div = createElement('div', 'event empty');
var span = createElement('span', '', 'No Events');
div.appendChild(span);
wrapper.appendChild(div);
}
if(currentWrapper) {
currentWrapper.className = 'events out';
currentWrapper.addEventListener('webkitAnimationEnd', function() {
currentWrapper.parentNode.removeChild(currentWrapper);
ele.appendChild(wrapper);
});
currentWrapper.addEventListener('oanimationend', function() {
currentWrapper.parentNode.removeChild(currentWrapper);
ele.appendChild(wrapper);
});
currentWrapper.addEventListener('msAnimationEnd', function() {
currentWrapper.parentNode.removeChild(currentWrapper);
ele.appendChild(wrapper);
});
currentWrapper.addEventListener('animationend', function() {
currentWrapper.parentNode.removeChild(currentWrapper);
ele.appendChild(wrapper);
});
} else {
ele.appendChild(wrapper);
}
}
Calendar.prototype.nextMonth = function() {
this.current.add('months', 1);
this.next = true;
this.draw();
}
Calendar.prototype.prevMonth = function() {
this.current.subtract('months', 1);
this.next = false;
this.draw();
}
window.Calendar = Calendar;
function createElement(tagName, className, innerText) {
var ele = document.createElement(tagName);
if(className) {
ele.className = className;
}
if(innerText) {
ele.innderText = ele.textContent = innerText;
}
return ele;
}
}();
!function() {
var data = [
{}
];
data.push({ eventName: 'test', calendar: 'Other', color: 'green', date:moment('2022-12-11T10:20:25')});
var partialsDates
const xhr = new XMLHttpRequest();
xhr.onload = () => {
partialDates = JSON.parse(xhr.responseText);
data.push({ eventName: 'Inicio de primer parcial', calendar: 'Other', color: 'green', date:moment(partialDates[0].startFirstPartial)});
data.push({ eventName: 'Inicio de segundo parcial', calendar: 'Other', color: 'green', date:moment(partialDates[0].startSecondPartial)});
data.push({ eventName: 'Inicio de tercer parcial', calendar: 'Other', color: 'green', date:moment(partialDates[0].startThirdPartial)});
console.log("a")
}
xhr.open("GET", "/api/timeAssignment/");
xhr.responseType = "text";
xhr.send();
var calendar = new Calendar('#calendar', data);
}();
I'm trying to push the information I grab with Ajax into the array data the events that I want the user to see, while it does add them to the array and successfully in the calendar, the function that draws a square doesn't seems to add the new elements in the array. This seems to be because the next function is called before:
todaysEvents.forEach(function(ev) {
var evSpan = createElement('span', ev.color);
element.appendChild(evSpan);
});
I don't really understand why that function is called before others like Calendar.prototype.renderEvents = function(events, ele) {}. Is there a way I can call it after adding elements to the array like the others? Is my approach incorrect?

Default filtering item

I have a page like this page:
http://www.sungeetheme.com/html/our_gallery_3_colums.html
In the filtering Gallery, the default item is "all"
How do I change the default to something else on page load, for example: Portrait?
I tried to change in the code section the variable dataFilterVal from "All" to something else and it did not work well
var masonryFilter = {
massMasonry: [],
dataFilterVal: "all",
init: function () {
var self = this;
self.filterEl('.j-filter', '~ .j-filter-content');
self.masonry();
},
masonry: function () {
var self = this;
var msnry;
var i = 0;
$('.j-masonry').each(function () {
var el = $(this),
newClass = 'j-masonry-' + i;
el.addClass(newClass).attr('data-masonry-id', i);
i++;
el.imagesLoaded(function () {
var container = document.querySelector('.' + newClass);
msnry = new Masonry(container,
{
itemSelector: '.j-masonry-item',
columnWidth: '.' + newClass + ' .masonry-gridSizer',
transitionDuration: '1.2s'
});
self.massMasonry.push(msnry);
el.data('masonry', msnry);
});
});
},
filterEl: function (filterNav, filterContent) {
var self = this;
$(filterNav + ' a').click(function (e) {
e.preventDefault();
var el = $(this);
var activeClass = "is-category-filter-active";
var activeContainer = $(filterContent, $(this).parents(filterNav)).eq(0);
console.log(activeContainer);
$('li', $(this).parents(filterNav)).removeClass(activeClass);
el.closest('li').addClass(activeClass);
self.dataFilterVal = el.attr('data-filter');
self.filterStart(self.dataFilterVal, activeContainer);
});
},
filterStart: function (dataFilterVal, filterContent) {
var self = this;
if (dataFilterVal == "all") {
$('[class*="j-filter-"]', filterContent).show().stop(true, false).animate({
opacity: 1
}, 400);
} else {
var hideItems = $('[class*="j-filter-"]', filterContent).not(dataFilterVal);
hideItems.stop(true, false).animate({
opacity: 0
}, 400);
setTimeout(function () {
hideItems.hide();
}, 301);
$(dataFilterVal, filterContent).show().stop(true, false).animate({
opacity: 1
}, 400);
}
setTimeout(function () {
var masonryId = $(filterContent).find('.j-masonry').attr('data-masonry-id');
self.massMasonry[masonryId].layout();
}, 501);
}
};
masonryFilter.init();

prevent slideshow from refresh or load content in div

I have a nice working image slideshow, but every time when i open a new page from the menu, the slideshow starts from the beginning. I want it to go on where it was while entering a new page. Now could there be a possibility to change it in the code of my slideshow, but maybe a better solution is to open my content in a div with AJAX, so the whole page doesn't refresh.
I found this on the web:
<div id="navigatie">
<div id="buttons">
<a class="menu" id="page1" href="#">Home</a><span>|</span>
<a class="menu" id="page2" href="#">Projects</a><span>|</span>
<a class="menu" id="page3" href="#">About</a><span>|</span>
</div>
</div>
<script>
$(document).ready(function() {
$("#page1").click(function(){
$('#content').load('index.php #content');
});
$("#page2").click(function(){
$('#content').load('projects.php #content');
});
$("#page3").click(function(){
$('#content').load('about.php #content');
});
});
</script>
But this doesn't workout very well because when i start with my index page and go to projects (where lightbox is present), i get full images instead of thumbnails.(This was because the extended files were not in #content) i get index.php# instead of projects.php. Maybe i should use an easier solution, but im getting stuck. Can someone help me out please?
Edit: Let me also share the code of the slideshow with you, perhaps there is a possibility to resume after loading a new page/refresh.
/*!
* crosscover v1.0.2
* Carousel of a simple background image using jquery and animate.css.
* http://git.blivesta.com/crosscover
* License : MIT
* Author : blivesta <enmt#blivesta.com> (http://blivesta.com/)
*/
;(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
'use strict';
var namespace = 'crosscover';
var __ = {
init: function(options) {
options = $.extend({
inClass: 'fade-in',
outClass: 'fade-out',
interval: 5000,
startIndex: 0,
autoPlay: true,
dotsNav: true,
controller: false,
controllerClass: 'crosscover-controller',
prevClass: 'crosscover-prev',
nextClass: 'crosscover-next',
playerClass: 'crosscover-player',
playerInnerHtml: '<span class="crosscover-icon-player"></span>',
prevInnerHtml: '<span class="crosscover-icon-prev"></span>',
nextInnerHtml: '<span class="crosscover-icon-next"></span>'
}, options);
__.settings = {
currentIndex: options.startIndex,
timer: null,
coverBaseClass:'crosscover-item',
coverWaitClass:'is-wait',
coverActiveClass:'is-active',
playerActiveClass: 'is-playing',
dotsNavClass: 'crosscover-dots'
};
return this.each(function() {
var _this = this;
var $this = $(this);
var data = $this.data(namespace);
var $item = $this.children('.crosscover-list').children('.' + __.settings.coverBaseClass);
if (!data) {
options = $.extend({}, options);
$this.data(namespace, {
options: options
});
if (options.dotsNav) __.createDots.call(_this, $item);
if (options.controller) __.createControler.call(_this, $item);
__.setup.call(_this, $item);
}
});
},
setup: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
$item.each(function(index) {
var $self = $(this);
var image = $self.find('img').attr('src');
$self
.addClass(__.settings.coverBaseClass, __.settings.coverWaitClass)
.css({
'background-image': 'url(' + image + ')'
});
});
return __.slideStart.call(_this, $item);
},
slideStart: function($item) {
var _this = this;
__.autoPlayStart.call(_this, $item);
__.show.call(_this, $item);
},
createDots: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var len = $item.length;
$this
.append(
$('<ul>')
.addClass(__.settings.dotsNavClass)
);
for (var i = 0; i < len; i++) {
$this
.children('.' + __.settings.dotsNavClass)
.append(
$('<li>')
.addClass('crosscover-dots-nav-' + i)
.append(
$('<button>')
)
);
}
__.addDots.call(_this, $item);
},
addDots: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var $dots = $this.children('.' + __.settings.dotsNavClass);
var $dot = $dots.children('li').children('button');
$dot.on('click.' + namespace, function(event) {
return __.toggle.call(_this, $item, 'dots', $(this).parent('li').index());
});
},
createControler: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var isClass = options.autoPlay ? __.settings.playerActiveClass : null;
$this
.append(
$('<div>')
.attr({
'data-crosscover-controller': ''
})
.addClass(options.controllerClass)
.append(
$('<button>')
.attr({
'data-crosscover-prev': ''
})
.addClass(options.prevClass)
.html(options.prevInnerHtml)
)
.append(
$('<button>')
.attr({
'data-crosscover-player': ''
})
.addClass(options.playerClass)
.addClass(isClass)
.html(options.playerInnerHtml)
)
.append(
$('<button>')
.attr({
'data-crosscover-next': ''
})
.addClass(options.nextClass)
.html(options.nextInnerHtml)
)
);
return __.addControler.call(_this, $item);
},
addControler: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var $controller = $this.children('[data-crosscover-controller]');
var $navPrev = $controller.children('[data-crosscover-prev]');
var $navNext = $controller.children('[data-crosscover-next]');
var $navPlayPause = $controller.children('[data-crosscover-player]');
$navPlayPause.on('click.' + namespace, function(event) {
$(this).blur();
return __.playToggle.call(_this, $item, $(this));
});
$navPrev.on('click.' + namespace, function(event) {
$(this).blur();
return __.toggle.call(_this, $item, 'prev');
});
$navNext.on('click.' + namespace, function(event) {
$(this).blur();
return __.toggle.call(_this, $item, 'next');
});
},
playToggle: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var $navPlayPause = $this.find('[data-crosscover-player]');
if (options.autoPlay) {
options.autoPlay = false;
$navPlayPause
.removeClass(__.settings.playerActiveClass)
.addClass(options.playClass);
return __.autoPlayStop.call(_this);
} else {
options.autoPlay = true;
$navPlayPause.addClass(__.settings.playerActiveClass);
return __.autoPlayStart.call(_this, $item);
}
},
toggle: function($item, setting, num) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
__.hide.call(_this, $item);
if (setting === 'next') {
__.settings.currentIndex++;
} else if (setting === 'prev') {
__.settings.currentIndex--;
} else if (setting === 'dots') {
__.settings.currentIndex = num;
}
if (__.settings.currentIndex >= $item.length) {
__.settings.currentIndex = 0;
} else if (__.settings.currentIndex <= -1) {
__.settings.currentIndex = $item.length - 1;
}
__.autoPlayStart.call(_this, $item);
return __.show.call(_this, $item);
},
show: function($item) {
var $this = $(this);
var options = $this.data(namespace).options;
if(options.dotsNav) {
$this
.children('.' + __.settings.dotsNavClass)
.children('li')
.eq(__.settings.currentIndex)
.addClass('is-active')
.children('button')
.prop('disabled', true);
}
return $item
.eq(__.settings.currentIndex)
.addClass(__.settings.coverActiveClass)
.removeClass(__.settings.coverWaitClass)
.addClass(options.inClass)
.csscallbacks('animationEnd',function() {
$(this)
.removeClass(options.inClass + ' ' + __.settings.coverWaitClass)
.addClass(__.settings.coverActiveClass);
});
},
hide: function($item) {
var $this = $(this);
var options = $this.data(namespace).options;
if(options.dotsNav) {
$this
.children('.' + __.settings.dotsNavClass)
.children('li')
.eq(__.settings.currentIndex)
.removeClass('is-active')
.children('button')
.prop('disabled', false);
}
return $item
.eq(__.settings.currentIndex)
.removeClass(__.settings.coverActiveClass)
.addClass(options.outClass)
.csscallbacks('animationEnd', function() {
$(this)
.removeClass(options.outClass + ' ' + __.settings.coverActiveClass)
.addClass(__.settings.coverWaitClass);
});
},
autoPlayStart: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
if (options.autoPlay) {
__.autoPlayStop.call(_this);
__.settings.timer = setTimeout(function() {
__.toggle.call(_this, $item, 'next');
__.autoPlayStart.call(_this, $item);
}, options.interval);
}
return _this;
},
autoPlayStop: function() {
return clearTimeout(__.settings.timer);
},
currentIndex: function() {
return __.settings.currentIndex;
}
};
$.fn.crosscover = function(method) {
if (__[method]) {
return __[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return __.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.' + namespace);
}
};
$.fn.csscallbacks = function(type, callback){
var _animationStart = 'animationstart webkitAnimationStart oAnimationStart';
var _animationEnd = 'animationend webkitAnimationEnd oAnimationEnd';
var _transitionEnd = "transitionend webkitTransitionEnd oTransitionEnd";
if(type === 'animationStart'){
type = _animationStart;
} else if(type === 'animationEnd'){
type = _animationEnd;
} else if(type === 'transitionEnd'){
type = _transitionEnd;
}
return this.each(function(index) {
var $this = $(this);
$this.on(type, function(){
$this.off(type);
return callback.call(this);
});
});
};
}));
Its fixed, i just load my content in the #content div and i changed every 'href' to #Home (or name i like) in combination with Benalman's hashchange script

Console displaying information of 4 objects when there is only 1 object in my array

I have the following code in angularjs:
TimeSlotsModel.all()
.then(function (result) {
vm.data = result.data.data;
var events = [];
angular.forEach(vm.data, function(value,key) {
var eventName = value.name;
var startDate = new Date(value.startDate);
var endDate = new Date(value.endDate);
var selectedStartingTime =new Date(value.startTime * 1000 );
var selectedEndingTime = new Date(value.endTime * 1000);
//timing is not right, needs fixing
startTime = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),selectedStartingTime.getHours(), selectedStartingTime.getUTCMinutes());
endTime = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),selectedEndingTime.getUTCHours(), selectedEndingTime.getUTCMinutes());
// console.log(startTime);
events.push({
title: 'Event -' + eventName,
startTime: startTime,
endTime: endTime,
allDay: false
});
console.log(eventName);
console.log(events);
// console.log(value);
//value is the object!!
})
return events;
$scope.$broadcast('eventSourceChanged',$scope.eventSource);
})
}
Everytime the forEach loop runs through my array of objects , vm.data, the console prints this:
My questions are :
1) Why are the details of the 4 objects being printed? Does it mean that for every object in the array it contains 4 other objects?
2) Is each object pushed to the events[ ] properly?
3) If the answer to question 2 is no, what should I do to resolve it?
EDIT: Updated code to using promise to return events array:
//Calendar Controller
.controller('CalendarCtrl', function ($scope,TimeSlotsModel,$rootScope,$q) {
var vm = this;
function goToBackand() {
window.location = 'http://docs.backand.com';
}
function getAll() {
TimeSlotsModel.all()
.then(function (result) {
vm.data = result.data.data;
});
}
function clearData(){
vm.data = null;
}
function create(object) {
TimeSlotsModel.create(object)
.then(function (result) {
cancelCreate();
getAll();
});
}
function update(object) {
TimeSlotsModel.update(object.id, object)
.then(function (result) {
cancelEditing();
getAll();
});
}
function deleteObject(id) {
TimeSlotsModel.delete(id)
.then(function (result) {
cancelEditing();
getAll();
});
}
function initCreateForm() {
vm.newObject = {name: '', description: ''};
}
function setEdited(object) {
vm.edited = angular.copy(object);
vm.isEditing = true;
}
function isCurrent(id) {
return vm.edited !== null && vm.edited.id === id;
}
function cancelEditing() {
vm.edited = null;
vm.isEditing = false;
}
function cancelCreate() {
initCreateForm();
vm.isCreating = false;
}
// initialising the various methods
vm.objects = [];
vm.edited = null;
vm.isEditing = false;
vm.isCreating = false;
vm.getAll = getAll;
vm.create = create;
vm.update = update;
vm.delete = deleteObject;
vm.setEdited = setEdited;
vm.isCurrent = isCurrent;
vm.cancelEditing = cancelEditing;
vm.cancelCreate = cancelCreate;
vm.goToBackand = goToBackand;
vm.isAuthorized = false;
//rootScope refers to the universal scope, .$on is a receiver for the
//message 'authorized'
$rootScope.$on('authorized', function () {
vm.isAuthorized = true;
getAll();
});
$rootScope.$on('logout', function () {
clearData();
});
if(!vm.isAuthorized){
$rootScope.$broadcast('logout');
}
initCreateForm();
getAll();
$scope.calendar = {};
$scope.changeMode = function (mode) {
$scope.calendar.mode = mode;
};
$scope.loadEvents = function () {
$scope.calendar.eventSource = getEvents();
$scope.$broadcast('eventSourceChanged',$scope.eventSource);
};
$scope.onEventSelected = function (event) {
console.log('Event selected:' + event.startTime + '-' + event.endTime + ',' + event.title);
};
$scope.onViewTitleChanged = function (title) {
$scope.viewTitle = title;
};
$scope.today = function () {
$scope.calendar.currentDate = new Date();
};
$scope.isToday = function () {
var today = new Date(),
currentCalendarDate = new Date($scope.calendar.currentDate);
today.setHours(0, 0, 0, 0);
currentCalendarDate.setHours(0, 0, 0, 0);
return today.getTime() === currentCalendarDate.getTime();
};
$scope.onTimeSelected = function (selectedTime) {
console.log('Selected time: ' + selectedTime);
};
function getEvents(object){
var deferred = $q.defer();
TimeSlotsModel.all()
.then(function (result) {
vm.data = result.data.data;
var events = [];
angular.forEach(vm.data, function(value,key) {
var eventName = value.name;
var startDate = new Date(value.startDate);
var endDate = new Date(value.endDate);
var selectedStartingTime = new Date(value.startTime * 1000 );
var selectedEndingTime = new Date(value.endTime * 1000);
//timing is not right, needs fixing
startTime = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),selectedStartingTime.getHours(), selectedStartingTime.getUTCMinutes());
endTime = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),selectedEndingTime.getUTCHours(), selectedEndingTime.getUTCMinutes());
// console.log(startTime);
events.push({
title: 'Event -' + eventName,
startTime: startTime,
endTime: endTime,
allDay: false
});
// console.log(eventName);
// console.log(events);
// console.log(value);
// console.log(key);
// console.log(value);
//value is the object!!
})
deferred.resolve(events);
// return events;
})
return deferred.promise;
console.log(deferred.promise);
}
[!Removed old answer]
I believe James is right here the console might be the culprit, I just reproduced the same behaviour.

jasmine test cases for the anonymous function

I need a jasmine code changes, but I have to complete set of jasmine for the anonymous function. I am new to this. I tried but, I'm not able to achieve fully. Please help me.
Html file
<div ng-class="{ 'mainPassdownFont mainPassdownNoteLayout noteEditBackground': isBeingEdited(note), 'mainPassdownFont mainPassdownNoteLayout': isNotBeingEdited(note) }" >
<textarea ng-attr-id="{{ 'note-' + note.PassdownNoteID }}" ng-show="isBeingEdited(note)" class="mainPassdownFont passdownTextAreaLayout">{{ note.NoteText }}</textarea>
<div ng-hide="isBeingEdited(note)" class="mainPassdownFont passdownTextAreaLayout">
<pre class="notePre">{{ note.NoteText }}</pre>
</div>
<input class="passdownNoteInlineCheckbox" ng-attr-id="{{ 'checkbox-' + note.PassdownNoteID }}" ng-model="cbModel" ng-change="checkBoxChanged(note)" ng-checked="isClaimed(note)" type="checkbox" name="notesCheckbox" value="notesCheckbox">
<div ng-show="isClaimed(note)" class="downArrowIcon passdownNoteDownArrowLayout" ></div>
<div ng-show="isClaimed(note)" class="passdownAnnotationFont claimTextContainerLayout" >
<p class="claimNameLayout">{{ note.Created.By.Text }}</p>
<p class="claimDateLayout">{{ note.Created.Date.Local | date : 'MMM d, y h:mm a' }}</p>
</div>
<div ng-hide="isClaimed(note)" ng-click="claimNote(note)" class="passdownAnnotationFont claimClickTextContainerLayout" >
<p class="claimNameLayout">Click to Claim</p>
</div>
<div class="passdownAnnotationFont authorTextContainerLayout" >
<p class="claimNameLayout">{{ note.LastModified.By.Text }}</p>
<p class="claimDateLayout">{{ note.LastModified.Date.Local | date : 'MMM d, y h:mm a' }}</p>
</div>
<div class="actionIconContainerLayout" >
<div class="deleteIcon inlineActionIconLayout" ng-click="deleteNote(note)"></div>
<div class="editIcon inlineActionIconLayout" ng-click="editNote(note)"></div>
<div class="addIcon inlineActionIconLayout" ng-click="addSubNote(note)"></div>
</div>
<div class="btnforpassdownTextAreaLayout">
<button ng-attr-id="{{ 'btn-' + note.PassdownNoteID }}" type="button" class="btn btnpassdownTextAreaLayout" ng-show="isBeingEdited(note)" ng-click="completeEdit(note)">Save</button>
<button ng-attr-id="{{ 'btn-' + note.PassdownNoteID }}" type="button" class="btn btnpassdownTextAreaLayout" ng-show="isBeingEdited(note)" ng-click="cancelEdit(note)">Cancel</button>
</div>
</div> </div>
</div>
</div>
js changes
app.controller('passdownCtrl',
['$rootScope', '$scope', '$http', '$resource', '$location', 'PassdownNotesData','$window', 'userService',
function($rootScope, $scope, $http, $resource, $location, PassdownNotesData, $window, userService) { $scope.passdownNotesData={ "reviewedDateUtc" : "01-01-2000T15:00", "results": [] };
$scope.reviewDate = null;
$scope.indexBeingEdited = -1;
$scope.inputfocus = false;
$scope.filterText = "";
// Go get trips from the server via an http Get Call. If successful, assign the response to
// $scope.tripData. If errors occur, assign them to the tripData for the UI to look for
// and provide the user some possible action.
$scope.passdownNotesData = PassdownNotesData.getData();
if ($scope.passdownNotesData.results.length == 0) {
PassdownNotesData.updatePassdownNotesData()
.then(function(result) {
$scope.passdownNotesData = result;
$scope.reviewDate = parseBoldIQDate(result.reviewedDateUtc); //error
}, function(error) {
alert('Error getting Passdown Notes data in controller');
});
} else {
//$scope.selectedRequestIndex = 0;
//$scope.selectedRequest = $scope.controllerRequestList.requestList[0];
}
parseBoldIQDate = function(dateStr) {
var newDate = new Date();
newDate.setUTCMonth(Number(dateStr.substr(0,2)) - 1);
newDate.setUTCDate(Number(dateStr.substr(3,2)));
newDate.setUTCFullYear(Number(dateStr.substr(6,4)));
newDate.setUTCHours(Number(dateStr.substr(11,2)));
newDate.setUTCMinutes(Number(dateStr.substr(14,2)));
return newDate;
};
$scope.noteState = function (cat, checkOpen) {
var containerName = cat + 'ContainerDiv';
var containerElement = document.getElementById(containerName);
if (containerElement != null) {
var isOpen = false;
if (containerElement.style.display == "block") {
isOpen = true;
}
return (isOpen == checkOpen);
}
return false;
};
getMaxNoteId = function() {
// create a new note structure, add it to the list, persist it, and put it in edit mode
var maxNoteId = 0;
for (var i = 0; i < $scope.passdownNotesData.results.length; i++ ) {
if ($scope.passdownNotesData.results[i].PassdownNoteID >= maxNoteId) {
maxNoteId = $scope.passdownNotesData.results[i].PassdownNoteID;
}
for (var j = 0; j < $scope.passdownNotesData.results[i].SubNotes.length; j++ ) {
if ($scope.passdownNotesData.results[i].SubNotes[j].PassdownNoteID >= maxNoteId) {
maxNoteId = $scope.passdownNotesData.results[i].SubNotes[j].PassdownNoteID;
}
}
}
return maxNoteId;
};
$scope.addNote = function(cat, event) {
// create a new note structure, add it to the list (local and global), persist it, and put it in edit mode
// create new note
var currentDate = new Date();
var newNote = new Object();
newNote.PassdownNoteID = getMaxNoteId() + 1;
newNote.Category = new Object();
newNote.Category.Text = cat;
newNote.NoteText = "Default Note Text";
newNote.Created = new Object();
// newNote.Created.ClaimStatus = "false";
newNote.Created.By = new Object();
newNote.Created.By.ID = 0;
newNote.Created.By.Text = "N/A";
newNote.Created.Date = new Object();
newNote.Created.Date.Utc = createBoldIQDate(currentDate);
newNote.Created.Date.Local = currentDate;
newNote.LastModified = new Object();
newNote.LastModified.By = new Object();
newNote.LastModified.By.ID = 17;
newNote.LastModified.By.Text = userService.getUser();
newNote.LastModified.Date = new Object();
newNote.LastModified.Date.Utc = createBoldIQDate(currentDate);
newNote.LastModified.Date.Local = currentDate;
newNote.SubNotes = new Array();
// Add it to local and global lists
//$scope.passdownNotesData.results[$scope.passdownNotesData.results.length] = newNote;
var dataCopy = PassdownNotesData.getData();
dataCopy.results[dataCopy.results.length] = newNote;
// Persist the updated data to the server
PassdownNotesData.writeUpdatesToServer(dataCopy);
// Put the display in Edit mode
$scope.indexBeingEdited = newNote.Id;
};
$scope.getNumUnclaimedForCategory = function(cat) {
var numUnclaimed = 0;
for (var i = 0; i < $scope.passdownNotesData.results.length; i++ ) {
if ($scope.passdownNotesData.results[i].Category.Text == cat) {
// If the main part of the note was updated, add 1 and call it good.
if ($scope.passdownNotesData.results[i].IsActive == "false") {
numUnclaimed++;
}
}
}
return numUnclaimed;
};
$scope.checkBoxChanged = function(note) {
var elementStr = "checkbox-" + note.PassdownNoteID;
var checkboxElement = document.getElementById(elementStr);
var val = checkboxElement.checked;
if (val == false) {
// Here we will unclaim the note
var dataCopy = PassdownNotesData.getDatacompleteSubNoteEdit();
// Update the real data 'and' our local scope copy, and write the real stuff back to the server
for (var i = 0; i < dataCopy.results.length; i++) {
if (note.PassdownNoteID == dataCopy.results[i].PassdownNoteID) {
console.log("inside here ", note.PassdownNoteID);
dataCopy.results[i].IsActive = "false";
//Update our local copy
$scope.passdownNotesData.results[i].IsActive = "false";
}
}
PassdownNotesData.writeUpdatesToServer(dataCopy); // $scope.passdownNotesData);
} else {
$scope.claimNote(note);
}
};
$scope.editSubNote = function(subNote) {
$scope.indexBeingEdited = subNote.PassdownNoteID;
var elementStr = "subNote-" + subNote.PassdownNoteID;
var textAreaElement = document.getElementById(elementStr);
$scope.subNotesText = textAreaElement.value;
};
$scope.isClaimed = function(note) {
if (note.isActive == "true") {
return true;
} else {
return false;
}
};
$scope.claimNote = function(note) {
var dataCopy = PassdownNotesData.getData();
// Update the real data 'and' our local scope copy, and write the real stuff back to the server
for (var i = 0; i < dataCopy.results.length; i++) {
if (note.PassdownNoteID == dataCopy.results[i].PassdownNoteID) {
dataCopy.results[i].isActive = "true";
dataCopy.results[i].Created.By.ID = 17;
dataCopy.results[i].Created.By.Text = $scope.loggedInUser;
var currentDate = new Date();
dataCopy.results[i].Created.Date.Utc = createBoldIQDate(currentDate);
dataCopy.results[i].Created.Date.Local = currentDate;
$scope.passdownNotesData.results[i].Created.Date.Utc = dataCopy.results[i].Created.Date.Utc;
$scope.passdownNotesData.results[i].Created.Date.Local = currentDate;
}
}
PassdownNotesData.writeUpdatesToServer(dataCopy); // $scope.passdownNotesData);
};
createBoldIQDate = function(date) {
var monthStr = (date.getUTCMonth() + 1).toString();
if (monthStr.length == 1) {
monthStr = "0" + monthStr;
}
var dateStr = (date.getUTCDate()).toString();
if (dateStr.length == 1) {
dateStr = "0" + dateStr;
}
var yearStr = (date.getUTCFullYear()).toString();
var hoursStr = (date.getUTCHours()).toString();
if (hoursStr.length == 1) {
hoursStr = "0" + hoursStr;
}
var minutesStr = (date.getUTCMinutes()).toString();
if (minutesStr.length == 1) {
minutesStr = "0" + minutesStr;
}
var dateStr = monthStr + "-" + dateStr + "-" + yearStr + "T" + hoursStr + ":" + minutesStr;
return dateStr;
};
$scope.filterTrips = function(note) {
if (note.Category.Text == 'Trips') { return true; } else { return false; }
};
$scope.filterWeather = function(note) {
if (note.Category.Text == 'Weather') { return true; } else { return false; }
};
$scope.filterMaintenance = function(note) {
if (note.Category.Text == 'Maintenance') { return true; } else { return false; }
};
$scope.filterGeneral = function(note) {
if (note.Category.Text == 'General') { return true; } else { return false; }
};
$scope.toggleNotesContainer = function(cat, event) {
var containerName = cat + 'ContainerDiv';
var containerElement = document.getElementById(containerName);
if (containerElement != null) {
if (containerElement.style.display == 'none') {
containerElement.style.display = 'block';
if (cat == "Trips") {
var buttonElement = document.getElementById("passdownToggleHideShowButton");
buttonElement.innerHTML = "Hide All";
}
} else {
containerElement.style.display = 'none';
if (cat == "Trips") {
var buttonElement = document.getElementById("passdownToggleHideShowButton");
buttonElement.innerHTML = "Show All";
}
}
}
};
$scope.toggleHideShowPassdown = function() {
// We will use the Trips container as the indicator of whether to "open All" or "Close all"
// TODO - when we get time, we want to animate the open/close of these containers
var tripsContainerElement = document.getElementById('TripsContainerDiv');
if (tripsContainerElement != null) {
if (tripsContainerElement.style.display == 'none') {
// This means we need to open all the containers, and change the text on the button to
// "hide all"
var buttonElement = document.getElementById("passdownToggleHideShowButton");
buttonElement.innerHTML = "Hide All";
var weatherContainerElement = document.getElementById('WeatherContainerDiv');
var maintenanceContainerElement = document.getElementById('MaintenanceContainerDiv');
var GeneralContainerElement = document.getElementById('GeneralContainerDiv');
tripsContainerElement.style.display = 'block';
weatherContainerElement.style.display = 'block';
maintenanceContainerElement.style.display = 'block';
GeneralContainerElement.style.display = 'block';
} else {
// This means we need to close all the containers, and change the text on the button to
// "show all"
var buttonElement = document.getElementById("passdownToggleHideShowButton");
buttonElement.innerHTML = "Show All";
var weatherContainerElement = document.getElementById('WeatherContainerDiv');
var maintenanceContainerElement = document.getElementById('MaintenanceContainerDiv');
var GeneralContainerElement = document.getElementById('GeneralContainerDiv');
tripsContainerElement.style.display = 'none';
weatherContainerElement.style.display = 'none';
maintenanceContainerElement.style.display = 'none';
GeneralContainerElement.style.display = 'none';
}
}
};
var containerElement = document.getElementById("TripsContainerDiv");
containerElement.style.display = 'block';
containerElement = document.getElementById("WeatherContainerDiv");
containerElement.style.display = 'block';
containerElement = document.getElementById("MaintenanceContainerDiv");
containerElement.style.display = 'block';
containerElement = document.getElementById("GeneralContainerDiv");
containerElement.style.display = 'block';
$scope.gotoPassdownScreen = function () {
//$location.path('#/requests/legDetails');
};
}]);
Jasmine js file..
describe('passdownnotes controller spec',function() {
var ctrlScope;
var rootScope;
var userServiceMock;
var PassdownNotesDataMock;
beforeEach(function() {
module('app'); // load jiops module
});
beforeEach(inject(function ($rootScope, $controller, $httpBackend, $q) {
ctrlScope = $rootScope.$new();
rootScope = $rootScope;
PassdownNotesDataMock = {
updatePassdownNotesData: function() {
var deferred = $q.defer();
deferred.resolve(mockPassdownNotesData);
return deferred.promise;
},
getData: function() {
return mockPassdownNotesData;
}
};
userServiceMock = {
getUser: function() {
var deferred = $q.defer();
deferred.resolve(mockUserData);
return deferred.promise;
}
};
$controller('passdownCtrl', {
$scope: ctrlScope,
PassdownNotesData:PassdownNotesDataMock,
userService:userServiceMock
});
}));
describe('passdownnotes controller',function() {
it('should have the correct initial configuration', function() {
expect(ctrlScope.indexBeingEdited).toEqual(-1);
expect(ctrlScope.inputfocus).toBe(false);
expect(ctrlScope.reviewDate).toBe(null);
expect(ctrlScope.passdownNotesData).toEqual(0);
expect(ctrlScope.filterText).toBe("");
});
});
});
var mockPassdownNotesData =
{
"results":[
{
"Created":{
"By":{
"ID":3,
"Text":"Developer, Jeppesen"
},
"Date":{
"Local":"07-02-2015T14:20:26",
"TzAbbrev":" MDT",
"Utc":"07-02-2015T20:20:26"
}
},
"IsActive":true,
"LastModified":{
"By":{
"ID":3,
"Text":"Developer, Jeppesen"
},
"Date":{
"Local":"07-02-2015T14:29:32",
"TzAbbrev":" MDT",
"Utc":"07-02-2015T20:29:32"
}
},
"NoteText":"test note3333",
"PassdownNoteID":1,
"AssignedTo":{
"ID":0,
"Text":""
},
"Category":{
"ID":692,
"Text":"Trips"
},
"DateAssigned":null,
"DueDate":{
"Local":"07-19-2015T18:00",
"TzAbbrev":" MDT",
"Utc":"07-20-2015T00:00"
},
"ExpirationDate":null,
"SubNotes":[
{
"Created":{
"By":{
"ID":3,
"Text":"Developer, Jeppesen"
},
"Date":{
"Local":"07-02-2015T14:20:27",
"TzAbbrev":" MDT",
"Utc":"07-02-2015T20:20:27"
}
},
"IsActive":true,
"LastModified":{
"By":{
"ID":3,
"Text":"Developer, Jeppesen"
},
"Date":{
"Local":"07-02-2015T14:20:27",
"TzAbbrev":" MDT",
"Utc":"07-02-2015T20:20:27"
}
},
"NoteText":"sample sub note",
"PassdownNoteID":2
}
]
},
{
"Created":{
"By":{
"ID":3,
"Text":"Developer, Jeppesen"
},
"Date":{
"Local":"07-07-2015T11:12:03",
"TzAbbrev":" MDT",
"Utc":"07-07-2015T17:12:03"
}
},
"IsActive":true,
"LastModified":{
"By":{
"ID":3,
"Text":"Developer, Jeppesen"
},
"Date":{
"Local":"07-07-2015T11:12:03",
"TzAbbrev":" MDT",
"Utc":"07-07-2015T17:12:03"
}
},
"NoteText":"Test Passdown Note",
"PassdownNoteID":3,
"AssignedTo":{
"ID":302,
"Text":"Button, Jenson"
},
"Category":{
"ID":695,
"Text":"General"
},
"DateAssigned":{
"Local":"07-07-2015T11:12",
"TzAbbrev":" MDT",
"Utc":"07-07-2015T17:12"
},
"DueDate":null,
"ExpirationDate":null,
"SubNotes":[
{
"Created":{
"By":{
"ID":3,
"Text":"Developer, Jeppesen"
},
"Date":{
"Local":"07-07-2015T11:12:03",
"TzAbbrev":" MDT",
"Utc":"07-07-2015T17:12:03"
}
},
"IsActive":true,
"LastModified":{
"By":{
"ID":3,
"Text":"Developer, Jeppesen"
},
"Date":{
"Local":"07-07-2015T11:12:03",
"TzAbbrev":" MDT",
"Utc":"07-07-2015T17:12:03"
}
},
"NoteText":"Test of passdown subnote",
"PassdownNoteID":4
}
]
}
]
};
describe('Controller: passdownCtrl', function() {
var $rootScope,
$scope,
$controller,
$http,
$resource,
PassdownNotesData,
$window,
userService,
ctrl;
// Mock required modules
angular.mock.module('PassdownNotesDataModule');
beforeEach(function(){
angular.mock.module(function($provide){
PassdownNotesData = jasmine.createSpyObj('PassdownNotesData', ['getData']);
// Optionally if you want service return some data
// PassdownNotesData.getData.and.returnValue({
// anyProperty: anyValue
// });
$provide.value('PassdownNotesData', PassdownNotesData);
});
});
beforeEach(function(){
angular.mock.module(function($provide){
userService = jasmine.createSpyObj('userService', ['getUser']);
// Optionally if you want service return some data
// userService.getUser.and.returnValue({
// anyProperty: anyValue
// });
$provide.value('userService', userService);
});
});
beforeEach(angular.mock.inject(function(_$rootScope_, _$controller_, _$http_, _$resource_, _PassdownNotesData_, _$window_, _userService_){
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$controller = _$controller_;
$http = _$http_;
$resource = _$resource_;
PassdownNotesData = _PassdownNotesData_;
$window = _$window_;
userService = _userService_;
ctrl = $controller('passdownCtrl as ctrl', {
$rootScope: $rootScope,
$scope: $scope,
$http: $http,
$resource: $resource,
PassdownNotesData: PassdownNotesData,
$window: $window,
userService: userService
});
}));
describe('on controller initialization', function(){
it('should set reviewDate', function(){
expect($scope.reviewDate).toBe(null);
});
it('should set indexBeingEdited', function(){
expect($scope.indexBeingEdited).toBe(-1);
});
it('should set inputfocus', function(){
expect($scope.inputfocus).toBe(false);
});
it('should set filterText ', function(){
expect($scope.filterText).toBe('');
});
});
describe('Function: passdownNotesData', function(){
it('should get data', function(){
$scope.passdownNotesData();
expect(PassdownNotesData.getData).toHaveBeenCalled();
})
});
...
});
Put any function and properties to the viewmodel of controller, not in the scope:
function SomeController(){
var vm = this;
vm.someProperty = ...;
vm.someFunction = someFunction;
function someFunction(){
....
}
}
app.controller('passdownCtrl', function($scope, PassdownNotesData) {
var vm = this;
vm.passdownNotesData = PassdownNotesData.getData();
if (vm.passdownNotesData.results.length == 0) {
PassdownNotesData.updatePassdownNotesData()
.then(function(result) {
vm.passdownNotesData = result;
vm.reviewDate = parseBoldIQDate(result.reviewedDateUtc);
}, function(error) {
alert('Error getting Passdown Notes data in controller');
});
}
var parseBoldIQDate = function(dateStr) {
var newDate = new Date();
newDate.setUTCMonth(Number(dateStr.substr(0, 2)) - 1);
newDate.setUTCDate(Number(dateStr.substr(3, 2)));
newDate.setUTCFullYear(Number(dateStr.substr(6, 4)));
newDate.setUTCHours(Number(dateStr.substr(11, 2)));
newDate.setUTCMinutes(Number(dateStr.substr(14, 2)));
return newDate;
};
});
describe('Controller: passdownCtrl', function(){
var $scope,
$controller,
$q,
deferred,
PassdownNotesData,
ctrl,
window;
beforeEach(angular.mock.module('requiredModule'));
beforeEach(function(){
angular.mock.module(function($provide){
PassdownNotesData = jasmine.createSpyObj('PassdownNotesData', ['getData', 'updatePassdownNotesData']);
$provide.value('PassdownNotesData', PassdownNotesData);
});
});
beforeEach(function(){
angular.mock.module(function($provide){
window = jasmine.createSpyObj('window', ['alert']);
$provide.value('window', window);
});
});
beforeEach(inject(function(_$rootScope_, _$controller_, _$q_, _PassdownNotesData_){
$scope = _$rootScope_.$new();
$controller = _$controller_;
$q = _$q_;
PassdownNotesData = _PassdownNotesData_;
deferred = $q.defer();
ctrl = $controller('passdownCtrl as ctrl', {
$scope: $scope,
PassdownNotesData: PassdownNotesData
});
}));
it('should resolve promise', function(){
var data = {
results: ['0']
}
var result = {
name: '0',
reviewedDateUtc: '12'
};
PassdownNotesData.getData.and.returnValue(data);
PassdownNotesData.updatePassdownNotesData.and.returnValue(deferred.promise);
deferred.resolve(result);
$scope.$digest();
expect(ctrl.passdownNotesData).toBe(result);
// function parseBoldIQDate must be executed with
// result.reviewedDateUtc value
expect(ctrl.reviewDate).toEqual('Thu Nov 30 0 02:00:50 GMT+0200 (FLE Standard Time)');
});
it('should reject promise', function(){
var data = {
results: ['0']
}
PassdownNotesData.getData.and.returnValue(data);
PassdownNotesData.updatePassdownNotesData.and.returnValue(deferred.promise);
deferred.reject({});
$scope.$digest();
expect(window.alert).toHaveBeenCalledWith('Error getting Passdown Notes data in controller');
});
});

Categories

Resources