jasmine test cases for the anonymous function - javascript

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');
});
});

Related

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

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!

i have a tempermonkey script which read data from csv file .....i want to change it based on fields on webpage

The script loads data from a CSV file. Page sometimes has five fields,
sometimes four. The script needs to adjust based on the number of fields.
forexample I need to modify this tempermonkey script
enter 4 pieces of data if there are 4 fields or enter 5 pieces of data if
there are 5 fields on the web page.
$(window).ready(function($) {
var file = GM_getResourceText('csvFile');
var csv = $.csv.toArrays(file);
var row = 0;
//var interval = setInterval(fillFormInterval, 3000);
var scope = angular.element($('body')).scope();
// scope.$on('$includeContentLoaded', function(){
// fillForm(csv[row]);
//setTimeout(fillForm(csv[row]));
//});
var interval = setInterval(fillFormInterval, 1000);
functionfillFormInterval() {
if($('#applicant-preferredCommunicationMethod').length) {
clearInterval(interval);
setTimeout(function() {
fillForm(csv[row]);
},3000);
}
}
functionfillForm(tempRow) {
var scope = angular.element($('#applicant-firstName')).scope();
if(!scope.applicant || !scope.applicant.phone1) {
return;
}
var row = new Array(5).fill(undefined);
row[1] = "NMN";
tempRow.forEach(function(data,i) {
if(data != '') {
row[i] = data;
}
});
scope.$apply(function() {
scope.applicant.firstName = row[0];
scope.applicant.middleName = row[1];
scope.applicant.lastName = row[2];
scope.applicant.dateOfBirth = row[3];
scope.applicant.dateOfBirth2 = row[3];
scope.applicant.phone1.number = row[4];
scope.applicant.preferredCommunicationMethod = "PHONE1";
scope.inherited.next();
});
//scope.applicant.countryOfBirth = "CD";
}
var interval_2 = setInterval(fillFormInterval_2, 1000);
function fillFormInterval_2() {
if($('#applicant-countryOfBirth').length) {
clearInterval(interval_2);
setTimeout(function() {
fillForm_2(csv[row]);
},3000);
}
}
functiondropDownVal(id, text) {
var value = null;
$(id).each(function() {
if(this.text.toLowerCase() == text) {
value = this.value;
value = value.split(':');
if(value.length> 1) {
value = value[1];
}else {
value = value[0];
}
}
});
return value;
}
function fillForm_2(data) {
var scope = angular.element($('#applicant-
countryOfBirth')).scope();
var country = '';
country = dropDownVal('#applicant-countryOfBirth option',
data[5].toLowerCase());
//scope.applicant.countryOfBirth = country;
var state = null;
scope.$apply(function() {
scope.applicant.countryOfBirth = country;
scope.updateStateProvince(scope.applicant.countryOfBirth);
setTimeout(function() {
if(country == "US" || country == "CD" || country == "MM") {
state = dropDownVal('#applicant-stateProvinceOfBirth
option', data[6].toLowerCase());
}
var citizen = dropDownVal('#applicant-countryOfCitizenship
option', data[7].toLowerCase());
console.log(country + " " + state + " " + citizen);
scope.applicant.countryOfCitizenship = citizen;
scope.applicant.stateProvinceOfBirth = state;
scope.$apply();
scope.inherited.next();
});
});
}
var interval_3 = setInterval(fillFormInterval_3, 1000);
function fillFormInterval_3() {
if($('.personal-questions').length) {
clearInterval(interval_3);
setTimeout(function() {
fillForm_3(csv[row]);
},3000);
}
}
function fillForm_3(data) {
e.applicant.hasMaidenPreviousName = false;
scope.applicant.hasAliasName = false;
scope.applicant.hasSameMailingResidentialAddress = true;
scope.applicant.doYouHaveAuthCode = false;
scope.applicant.viewEcNearYou = false;
scope.inherited.next();
});
}
var interval_4 = setInterval(fillFormInterval_4, 1000);
function fillFormInterval_4() {
if($('#ue-btn-US').length) {
clearInterval(interval_4);
setTimeout(function() {
fillForm_4(csv[row]);
},3000);
}
}
function fillForm_4(data) {
var scope = angular.element($('#applicant-eyeColor')).scope();
scope.$apply(function() {
scope.heightFt = parseInt(data[8].substr(0,1));
scope.heightIn = parseInt(data[8].substr(1,3));
scope.weightLb = parseInt(data[9]);
scope.applicant.hairColor = dropDownVal('#applicant-hairColor
option',
data[10].toLowerCase());
scope.applicant.eyeColor = dropDownVal('#applicant-eyeColor
option',
data[11].toLowerCase());
scope.applicant.gender = dropDownVal('#applicant-gender
option',
data[12].toLowerCase());
if(data[13].toLowerCase() == 'mixed race') {
data[13] = 'Unknown';
}else if(data[13].toLowerCase() == 'white' ||
data[13].toLowerCase() ==
'hispanic') {
data[13] = 'Caucasian/Latino';
}
scope.applicant.race = dropDownVal('#applicant-race option',
data[13].toLowerCase());
scope.inherited.next();
});
}
var interval_5 = setInterval(fillFormInterval_5, 1000);
function fillFormInterval_5() {
if($('#applicant-mailingAddress-country').length) {
clearInterval(interval_5);
setTimeout(function() {
fillForm_5(csv[row]);
},3000);
}
}
function fillForm_5(data) {
var scope = angular.element($('#applicant-mailingAddress-
country')).scope();
scope.$apply(function() {
scope.applicant.mailingAddress = {};
scope.applicant.mailingAddress.country = "US";
scope.updateStates('mailingAddress');
scope.applicant.mailingAddress.addressLine1 = data[14];
scope.applicant.mailingAddress.addressLine2 = data[15];
scope.applicant.mailingAddress.city = data[16];
setTimeout(function() {
scope.$apply(function() {
scope.applicant.mailingAddress.state = dropDownVal('#applicant-
mailingAddress-state option', data[17].toLowerCase());
scope.applicant.mailingAddress.postalCode = data[18];
scope.inherited.next();
});
});
//scope.inherited.next();
});
}
var interval_6 = setInterval(fillFormInterval_6, 1000);
function fillFormInterval_6() {
if($('#designatedRecipient-name').length) {
clearInterval(interval_6);
setTimeout(function() {
fillForm_6(csv[row]);
},3000);
}
}
function fillForm_6(data) {
var scope = angular.element($('#designatedRecipient-
name')).scope();
scope.$apply(function() {
scope.applicant.designatedRecipientName = "BIOVERIFY INC";
scope.applicant.designatedRecipientAddress = {};
scope.applicant.designatedRecipientAddress.country = "US";
scope.applicant.designatedRecipientAddress.addressLine1 = "2535
Manana
Dr.";
scope.applicant.designatedRecipientAddress.city = "Dallas";
setTimeout(function() {
scope.$apply(function() {
scope.applicant.designatedRecipientAddress.state =
dropDownVal('#applicant-designatedRecipientAddress-state
option', 'texas');
scope.applicant.designatedRecipientAddress.postalCode =
"75220";
scope.inherited.next();
});
});
scope.updateStates();
});
}
var interval_7 = setInterval(fillFormInterval_7, 1000);
function fillFormInterval_7() {
if($('#payment-nameOnCard').length) {
clearInterval(interval_7);
setTimeout(function() {
fillForm_7(csv[row]);
},3000);
}
}
function fillForm_7(data) {
var scope = angular.element($('#payment-nameOnCard')).scope();
scope.$apply(function() {
scope.applicant.payment.nameOnCard = "Brendan J Berrells";
scope.applicant.payment.cardNumber = "4246315197117185";
scope.applicant.payment.expiration = {};
scope.applicant.payment.expiration.month = 11;
scope.applicant.payment.expiration.year = "19";
scope.applicant.payment.csc = "255";
});
}
});

Protractor with Page Object Model ( Typescript error )

I was trying to create a POM for one test in Protractor, but I always get this error that Page not defined this is my Code in POM:`
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
class MainMenuPage {
constructor() {
this.get = function() {
browser.get('http://localhost:5000');
}
this.browserSleep = function () {
return browser.sleep(1000);
}
this.getUploadButtonText = function() {
return element(by.css('.mat-button-wrapper')).getText();
}
this.getBrowserTitle = function() {
return browser.getTitle();
}
this.getNavBarText = function() {
return element(by.css('.navbar-brand')).getText();
}
this.getNavBarUrl = function() {
return element(by.css('.navbar-brand')).browser.getCurrentUrl();
}
this.getHomeBtnText = function() {
return element(by.css('.link-active a')).getText();
}
this.getHomeBtnUrl = function() {
return element(by.css('.link-active a')).browser.getCurrentUrl();
}
this.getPageTitleText = function() {
return element(by.css('div.col-sm-10.body-content > app-management-overview > h1')).getText();
}
this.getUploadSisBtnText = function() {
return element(by.css('.mat-button-wrapper')).getText();
}
this.clickUploadSisBtn = function() {
return element(by.css('.mat-button-wrapper')).click();
}
this.getAddFilesBtnText = function() {
return element(by.css('.add-files-btn')).getText();
}
this.getUploadSisDialogCancelBtnText = function() {
return element(by.css('button.mat-button.ng-star-inserted')).getText();
}
this.getUploadSisDialogUploadBtnText = function() {
return element(by.css('button.mat-raised-button.mat-primary')).getText();
}
this.clickUploadSisDialogCancelBtn = function() {
return element(by.css('button.mat-button.ng-star-inserted')).click();
};
this.uploadPackageonUploadSisDialog = function() {
return element(by.css('.add-files-btn'));
};
this.clickOnUploadBtnInUploadSisDialog = function() {
return element(by.css('button.mat-raised-button.mat-primary')).click();
};
this.getNamesOfTheHeadRowTableText = function() {
return element.all(by.css('.table th'))
.then(function(resultH) {
var H00 = (resultH[0]);
var H01 = (resultH[1]);
var H02 = (resultH[2]);
var H03 = (resultH[3]);
var H04 = (resultH[4]);
});
};
this.getNamesOfBodyRowTableText = function() {
element.all(by.css('.table td'))
.then(function(resultB) {
var B00 = (resultB[0]);
var B01 = (resultB[1]);
var B02 = (resultB[2]);
var B03 = (resultB[3]);
var B04 = (resultB[4]);
return element.all(by.css('.table app-provision button'))
}).then(function(resultB04Btn) {
B04B0 = (resultB04Btn[0]);
B04B1 = (resultB04Btn[1]);
return element.all(by.css('.table option'))
}).then(function(resultB02) {
B02S0 = (resultB02[0]);
B02S1 = (resultB02[1]);
});
}
}
}
exports.MainMenuPage = MainMenuPage;
and this is my Spec file: `
'use strict';
`Object.defineProperty(exports, "__esModule", { value: true });
var Page = require('../Pages/Ks.Sis.ServiceApp.Po.js');
let MainMenuPage1 = new Page();
describe('it should test Ks.Sis.AppStore.Web automatically ', function() {
MainMenuPage1.get();
it('Should check if the Name of the Title is correct',function() {
expect(MainMenuPage1.getBrowserTitle()).toBe("Ks.Sis.AppStore.Web");
});
it('should check if the name of the Navbar is correct', function(){
expect(MainMenuPage1.getNavBarText()).toBe("Ks.Sis.ServiceApp")
});
it('should check if the Url of Navbar is correct ',function() {
var NavBar = element(by.css('.navbar-brand'));
return expect(browser.getCurrentUrl(NavBar)).toEqual("http://localhost:5000/app-management");
//expect(getNavBarUrl()).toEqual("http://localhost:5000/app-management")
});
it('should check if the name of Homebtn is correct', function() {
expect(MainMenuPage1.getHomeBtnText()).toBe("Applications")
});
it("should check if the Url of the Homebtn is correct", function() {
var HomeBtnUrl = element(by.css('.link-active a'));
return expect(browser.getCurrentUrl(HomeBtnUrl)).toEqual("http://localhost:5000/app-management");
//expect(getHomeBtnUrl()).toEqual("http://localhost:5000/app-management")
});
it('should check if the name of the Home page Overview is correct', function() {
expect(MainMenuPage1.getPageTitleText()).toEqual("Application Management")
});
it('should check if the name of the UploadSisBtn is correct', function() {
expect(MainMenuPage1.getUploadSisBtnText()).toBe("Upload Sis Package")
});
it('should check if the name of the Add Files Btn is correct', function() {
MainMenuPage1.clickUploadSisBtn()
MainMenuPage1.browserSleep()
MainMenuPage1.expect(getAddFilesBtnText()).toBe("Add Files")
});
it('Should check if the name of UploadDialogCancelBtn is correct',function() {
MainMenuPage1.clickUploadSisBtn()
MainMenuPage1.browserSleep()
MainMenuPage1.expect(getUploadSisDialogCancelBtnText()).toBe('Cancel');
});
it('Should check if the name of UploadDialogUploadBtn is correct',function() {
MainMenuPage1.clickUploadSisBtn()
MainMenuPage1.browserSleep()
MainMenuPage1.expect(getUploadSisDialogUploadBtnText()).toBe('Upload');
});
it('Should open the UploadSisDialog and close it with CancelBtn',function() {
MainMenuPage1.clickUploadSisBtn()
MainMenuPage1.browserSleep()
MainMenuPage1.clickUploadSisDialogCancelBtn()
MainMenuPage1.browserSleep()
});
it('Should open the UploadSisDialog and upload a package',function() {
var path = require('path');
var fileToUpload = 'C:\App-Store\Application1Type.1.0.0.nupkg';
absolutePath = path.resolve(__dirname, fileToUpload);
MainMenuPage1.clickUploadSisBtn();
MainMenuPage1.browserSleep();
MainMenuPage1.uploadPackageonUploadSisDialog().sendKeys(absolutePath);
MainMenuPage1.browserSleep();
MainMenuPage1.clickOnUploadBtnInUploadSisDialog();
MainMenuPage1.browserSleep();
});
it('should check if the names of the HeadRow Table are correct', function() {
MainMenuPage1.getNamesOfTheHeadRowTableText()
return element.all(by.css('.table th'))
.then(function(resultH) {
var H00 = (resultH[0]);
var H01 = (resultH[1]);
var H02 = (resultH[2]);
var H03 = (resultH[3]);
var H04 = (resultH[4]);
expect(H00.getText()).toEqual("Applications");
expect(H01.getText()).toEqual("Installed");
expect(H02.getText()).toEqual("Package");
expect(H03.getText()).toEqual("Dependencies");
expect(H04.getText()).toEqual("Provision");
});
});
it('should check if names of the BodyRows table are correct', function () {
MainMenuPage1.getNamesOfBodyRowTableText()
return element.all(by.css('.table td'))
.then(function(resultB) {
var B00 = (resultB[0]);
var B01 = (resultB[1]);
var B02 = (resultB[2]);
var B03 = (resultB[3]);
var B04 = (resultB[4]);
expect(B00.getText()).toEqual("Application1Type");
expect(B01.getText()).toEqual("");
expect(B03.getText()).toEqual("Show");
return element.all(by.css('.table app-provision button'))
})
.then(function(resultB04Btn) {
B04B0 = (resultB04Btn[0]);
B04B1 = (resultB04Btn[1]);
expect(B04B0.getText()).toEqual("install");
expect(B04B1.getText()).toEqual("uninstall");
return element.all(by.css('.table option'))
})
.then(function(resultB02) {
B02S0 = (resultB02[0]);
B02S1 = (resultB02[1]);
expect(B02S0.getText()).toEqual("1.0.0");
expect(B02S1.getText()).toEqual("1.1.0");
});
})
});
And this error I am getting,
[chrome #11] [14:02:04] I/hosted - Using the selenium server at
http://localhost:4444/wd/hub [chrome #11] [14:02:06] I/runnerCli -
Page is not a constructor
any help ?
thanks
You are using a named export for MainMenuPage but your test is importing it as though it were exported by assigning to module.exports itself (module.exports = MainMenuPage). This will cause the above error.
Import it correctly in your test
var Page = require('../Pages/Ks.Sis.ServiceApp.Po.js');
let MainMenuPage1 = new Page.MainMenuPage();

TypeError: Cannot create property 'style' on string 'a'

Honestly do not know whats happen, this was working this morning, have not changed a thing but now when i click my button to generate my images I get this error.
Can anyone tell me why and how to fix this please.
Error
test initMock test generate 1
TypeError: Cannot create property 'style' on string 'a'
at i._createCanvasElement (fabric.min.js:2)
at i._createLowerCanvas (fabric.min.js:2)
at i._initStatic (fabric.min.js:2)
at initialize (fabric.min.js:3)
at new i (fabric.min.js:1)
at b.$scope.uploadImage (controller.js:855)
at b.$scope.generate (controller.js:929)
at fn (eval at compile (angular.js:15500), <anonymous>:4:144)
at e (angular.js:27285)
at b.$eval (angular.js:18372)
my functions
$scope.uploadImage = function (where) {
var deferred = $q.defer();
if (where === 'upload') {
var f = document.getElementById('uploadCreative').files[0];
var r = new FileReader();
r.onload = function () {
var image = new Image();
image.src = r.result;
image.onload = function () {
$scope.resize(image.src).then(function (response) {
deferred.resolve(response);
console.log('hehe NO!');
console.log('hehe NO!');
}).catch(function (response) {
})
}
};
r.readAsDataURL(f);
}
if (where === 'local') {
function ax(a, callback) {
callback(localStorage.getItem(a));
}
var loadCanvas = new fabric.Canvas('a');
divHeight = $('.image-builder').height();
if ($scope.format === '1') {
Aratio = 0.67;
} else if ($scope.format === '2') {
Aratio = 0.56;
} else if ($scope.format === '3') {
divHeight = divHeight / 1.5;
Aratio = 2;
} else if ($scope.format === '4') {
Aratio = 0.67;
} else {
Aratio = 1
}
loadCanvas.setHeight(divHeight - 15);
loadCanvas.setWidth((divHeight - 15) * Aratio);
if (localStorage.getItem('backgroundImage') !== 'null') {
background = localStorage.getItem('backgroundImage');
var imgBc = new Image();
imgBc.onload = function () {
// this is syncronous
Iwidth = this.width;
Iheight = this.height;
var f_img = new fabric.Image(imgBc);
loadCanvas.setBackgroundImage(f_img, loadCanvas.renderAll.bind(loadCanvas), {
scaleY: loadCanvas.height / Iheight,
scaleX: loadCanvas.width / Iwidth
});
var test = ax('CC-canvas', function (response) {
loadCanvas.loadFromJSON(response, function () {
loadCanvas.renderAll();
$scope.resize(loadCanvas.toDataURL()).then(function (response) {
deferred.resolve(response);
}).catch(function (response) {
})
});
});
};
imgBc.src = background;
} else {
var test = ax('CC-canvas', function (response) {
loadCanvas.loadFromJSON(response, function () {
loadCanvas.renderAll();
$scope.resize(loadCanvas.toDataURL()).then(function (response) {
deferred.resolve(response);
}).catch(function (response) {
console.log(response);
})
});
});
}
}
return deferred.promise;
};
$scope.generate = function () {
$scope.generating = true;
$scope.generateBtn = 'Generating';
for (i = 0; i < $scope.gallery.length; i++) {
$scope.select[i] = '';
}
$scope.gallery = [];
$scope.checkPhoto = [];
console.log("test generate 1");
$scope.uploadImage($scope.creative).then(function (result) {
console.log("test generate 2");
$scope.generateCanvas(result, $scope.left, $scope.tops, $scope.wi, $scope.hi, $scope.per, $scope.btmR, $scope.btmL, $scope.backUrl)
.then(function () {
$timeout(function () {
//push final photo to array befor send to back end
$scope.photosToPhp.push(canvas2.toDataURL());
}, 800);
if ($scope.count < ($scope.photos[$scope.format].length - 1)) {
$scope.generate();
$scope.count++;
$scope.left = $scope.photos[$scope.format][$scope.count]['left'];
$scope.tops = $scope.photos[$scope.format][$scope.count]['tops'];
$scope.wi = $scope.photos[$scope.format][$scope.count]['wi'];
$scope.hi = $scope.photos[$scope.format][$scope.count]['hi'];
$scope.per = $scope.photos[$scope.format][$scope.count]['per'];
$scope.btmR = $scope.photos[$scope.format][$scope.count]['btmR'];
$scope.btmL = $scope.photos[$scope.format][$scope.count]['btmL'];
$scope.backUrl = "/mm3/public/img/formats/" + $scope.format + "/" + $scope.photos[$scope.format][$scope.count]['backUrl'];
$scope.$apply();
console.log("test generate 3");
} else {
//all photos've been pushed now sending it to back end
$timeout(function () {
// console.log($scope.photosToPhp[0]);
$http.post('/mm3/savePhoto', $scope.photosToPhp).then(function (success) {
$scope.generating = false;
$scope.generateBtn = 'Generate';
//creating mock up gallery
for (var x = 0; x < success.data.photos; x++) {
var file = '/mm3/tmp/' + success.data.folder + "/out" + x + ".png";
$scope.gallery.push(file);
}
$scope.photosToPhp = [];
}, function (error) {
});
}, 800);
$scope.count = 0;
$scope.left = $scope.photos[$scope.format][$scope.count]['left'];
$scope.tops = $scope.photos[$scope.format][$scope.count]['tops'];
$scope.wi = $scope.photos[$scope.format][$scope.count]['wi'];
$scope.hi = $scope.photos[$scope.format][$scope.count]['hi'];
$scope.per = $scope.photos[$scope.format][$scope.count]['per'];
$scope.btmR = $scope.photos[$scope.format][$scope.count]['btmR'];
$scope.btmL = $scope.photos[$scope.format][$scope.count]['btmL'];
$scope.backUrl = "/mm3/public/img/formats/" + $scope.format + "/" + $scope.photos[$scope.format][$scope.count]['backUrl'];
$scope.$apply();
}
console.log("test generate 4");
})
.catch(function (errorUrl) {
console.log(errorUrl);
})
})
};
Solved bu downgrading fabric js to 1.5 not 1.7 that i upgraded to, dont know why this worked but it dose

element.val() returning previous value

Here is my problem
I am trying to create a button that calls a directive function which then activates the google place 'place_changed' event that is assigned to the directive. If the getPlace() function doesn't return a result e.g. var result = scope.gPlace.getPlace(); then I want force a place prediction by doing the following.
if( result === undefined ) {
result = { name: element.val() }
}
however the problem is that this code will work when the page is first loaded but subsequent attempts will assign the var result to the previous text that was entered. e.g. Type "Adelaide" and click on the button equals successful process however now type melbourne and click on the button will still equal "Adelaide"
'use strict';
angular.module( "ngAutocomplete", [])
.directive('ngAutocomplete', function() {
return {
require: 'ngModel',
scope: {
ngModel: '=',
options: '=?',
details: '=?',
setFn: '&'
},
link: function(scope, element, attrs, controller) {
//options for autocomplete
var opts
var watchEnter = false
//convert options provided to opts
var initOpts = function() {
opts = {}
if (scope.options) {
if (scope.options.watchEnter !== true) {
watchEnter = false
} else {
watchEnter = true
}
if (scope.options.types) {
opts.types = []
opts.types.push(scope.options.types)
scope.gPlace.setTypes(opts.types)
} else {
scope.gPlace.setTypes([])
}
if (scope.options.bounds) {
opts.bounds = scope.options.bounds
scope.gPlace.setBounds(opts.bounds)
} else {
scope.gPlace.setBounds(null)
}
if (scope.options.country) {
opts.componentRestrictions = {
country: scope.options.country
}
scope.gPlace.setComponentRestrictions(opts.componentRestrictions)
} else {
scope.gPlace.setComponentRestrictions(null)
}
}
}
if (scope.gPlace == undefined) {
scope.gPlace = new google.maps.places.Autocomplete(element[0], {});
}
google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
var result = scope.gPlace.getPlace();
//hack to make sure we have an object to pass to ensure we can get results from the called function activateGetPlace
if( result === undefined ) {
result = { name: element.val() }
}
console.log("the result", result);
if (result !== undefined) {
if (result.address_components !== undefined) {
scope.$apply(function() {
scope.details = result;
controller.$setViewValue(element.val());
});
}
else {
if (watchEnter) {
getPlace(result)
}
}
}
})
//function to get retrieve the autocompletes first result using the AutocompleteService
var getPlace = function(result) {
var autocompleteService = new google.maps.places.AutocompleteService();
if (result.name.length > 0){
autocompleteService.getPlacePredictions(
{
input: result.name,
offset: result.name.length,
types: opts.types,
componentRestrictions: opts.componentRestrictions
},
function listentoresult(list, status) {
if(list == null || list.length == 0) {
scope.$apply(function() {
scope.details = null;
});
} else {
var placesService = new google.maps.places.PlacesService(element[0]);
placesService.getDetails(
{'reference': list[0].reference},
function detailsresult(detailsResult, placesServiceStatus) {
if (placesServiceStatus == google.maps.GeocoderStatus.OK) {
scope.$apply(function() {
controller.$setViewValue(detailsResult.formatted_address);
element.val(detailsResult.formatted_address);
scope.details = detailsResult;
//on focusout the value reverts, need to set it again.
var watchFocusOut = element.on('focusout', function(event) {
element.val(detailsResult.formatted_address);
element.unbind('focusout')
})
});
}
}
);
}
});
}
}
controller.$render = function () {
var location = controller.$viewValue;
element.val(location);
};
//watch options provided to directive
scope.watchOptions = function () {
return scope.options
};
scope.$watch(scope.watchOptions, function () {
initOpts()
}, true);
scope.activateGetPlace = function() {
google.maps.event.trigger(scope.gPlace, 'place_changed');
}
scope.setFn({theDirFn: scope.activateGetPlace});
}
};
});
var mechanicsearch = angular.module('mechanicsearch', ['ngRoute','ngResource','ngAutocomplete']),
radiusOptions = [];
mechanicsearch.run(function($rootScope) {
$rootScope.$on('handleActiveJobsPanel', function(event, args) {
$rootScope.$broadcast('activateJobsPanel', args);
});
$rootScope.$on('handleActiveFinalise', function(event, args) {
$rootScope.$broadcast('activateFinalisePanel', args);
});
$rootScope.$on('handleActiveSearch', function(event, args) {
$rootScope.$broadcast('activateSearchPanel', args);
});
});
mechanicsearch.filter('htmlToPlaintext', function() {
return function(text) {
return text ? String(text).replace(/<[^>]+>/gm, '') : '';
};
});
// mechFactory service
mechanicsearch.factory('mechFactory', function($resource,$window) {
var mechanics = [];
var jobs = [];
var addMechanic = function(mechanic){
mechanics.push(mechanic);
};
var getAllMechanics = function(){
return mechanics;
};
var removeAllMechanics = function() {
mechanics = [];
}
var addJob = function(job) {
jobs.push(job);
}
var getAllJobs = function() {
return jobs;
}
var removeAllJobs = function() {
jobs = [];
}
return {
getMechanics: function(location,radius) {
return $resource('/ajax/api.cfm?api=mechanic&function=getMechanicByLocation&lat=:lat&lng=:lng&radius=:radius' ).get({lat:location.lat,lng:location.lng,radius:radius});
},
getJobs: function() {
return $resource('/ajax/api.cfm?api=job&function=getJobsAssignedtoWorkshop' ).get();
},
sendMechanicsJobNotifications: function(mechanics, jobs) {
return $resource('/ajax/api.cfm?api=job&function=sendMechanicsJobNotifications&mechanics=:mechanics&jobs=:jobs' ).get({mechanics:mechanics.toString(),jobs:jobs.toString()});
},
addMechanic: addMechanic,
removeAllMechanics: removeAllMechanics,
getAllMechanics: getAllMechanics,
addJob: addJob,
removeAllJobs: removeAllJobs,
getAllJobs: getAllJobs
}
});
mechanicsearch.controller('SearchCtrl', ['$timeout', '$scope', '$window', '$location', '$routeParams', 'filterFilter', 'mechFactory', '$resource', '$element',
function ($timeout, $scope, $window, $location, $routeParams, filterFilter, mechFactory, $resource, $element) {
$scope.place = {};
$scope.place.address = null;
$scope.place.lat = null;
$scope.place.lng = null;
$scope.radius = 25;
$scope.mechanics = [];
$scope.selection = [];
$scope.alert = null;
$scope.showSearchPanel = true;
//Helper method to get selected mechanics
$scope.selectedMechanics = function selectedMechanics() {
filterFilter($scope.mechanics, { selected: true })
};
//allow mechanic checkbox to select/deselect on click
$scope.toggleMechanicSelect = function(mechanic) {
mechanic.selected = !mechanic.selected;
}
$scope.goToJobListing = function() {
$scope.showSearchPanel = false;
mechFactory.removeAllMechanics();
for( var i in $scope.selection ) {
mechFactory.addMechanic($scope.selection[i]);
}
$scope.$emit('handleActiveJobsPanel');
}
// watch mechanics for changes
$scope.$watch('mechanics|filter:{selected:true}', function (nv) {
$scope.selection = nv.map(function (mechanic) {
return mechanic.objectid;
});
}, true);
//watch the returning google autocomplete details object
$scope.$watch('details', function() {
if( $scope.details !== undefined && $scope.details !== null ) {
$scope.place.address = $scope.details.formatted_address;
$scope.place.lat = $scope.details.geometry.location.lat();
$scope.place.lng = $scope.details.geometry.location.lng();
}
});
// watch the $scope.place data for changes
$scope.$watchCollection('place', function() {
if( $scope.place.lat !== null || $scope.place.lng !== null ) {
$scope.getMechanics();
}
});
$scope.$watch('radius', function() {
if( Number.isInteger(parseInt($scope.radius)) ){
$scope.getMechanics();
}
});
$scope.setDirectiveFn = function(directiveFn) {
$scope.directiveFn = directiveFn;
};
$scope.getMechanics = function() {
mechFactory.getMechanics($scope.place, $scope.radius).$promise.then(
function successfulResult (mechanicsData) {
if (!mechanicsData || !mechanicsData.data.length){
$scope.alert = 'Sorry, no mechanic found in "' + $scope.place.address + '" with radius of ' + $scope.radius + '.';
$scope.mechanics = [];
$scope.selection = [];
} else {
$scope.alert = mechanicsData.data.length + ' mechanic(s) found in "' + $scope.place.address + '" with radius of ' + $scope.radius + ' km.';
$scope.mechanics = mechanicsData.data;
$scope.selection = [];
}
}, function failedResult (err) {
$scope.alert = err.message;
});
};
//display panel once we have recieved the event
$scope.$on('activateSearchPanel', function(event, args) {
$scope.mechanics = [];
$scope.selection = [];
$scope.alert = null;
$scope.showSearchPanel = true;
$scope.place = {};
$scope.radius = 25;
});
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-route.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-resource.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCmN0htBqG3DGo04KKKzC9srgIrhP0Dq5o&libraries=places"></script>
<div id="mechanicsearch" data-ng-app="mechanicsearch">
<div data-ng-controller="SearchCtrl" ng-show="showSearchPanel">
<aside class="workshopsearch" >
<form method="post" class="form-inline" role="form">
<div class="row">
<div class="col-sm-6 form-group input-group-lg">
<input type="text" id="geoSearch" ng-model="autocomplete" class="form-control" ng-autocomplete options="{ types: 'geocode', country: 'au', watchEnter: true }" details="details" set-fn="setDirectiveFn(theDirFn)" />
</div>
<div class="col-sm-6 input-group input-group-lg">
<input type="text" class="form-control" name="radius" id="radius" placeholder="Radius" data-ng-model="radius">
<span class="input-group-btn"><button class="btn btn-go" ng-click="directiveFn()">Go</button</span>
</div>
</div>
</form>
</aside>
</div>
</div>
}
Why are you using element.val() when you have an ngModel bound to the input? Why not use scope.ngModel instead?

Categories

Resources