Reset table preferences with angular js - javascript

I have the following table in my application where user can set their notification preferences.
when the page loads the $ctrl.getNotificationSettings() will be invoked and it will list the users notification preferences for various categories.please refer screenshot
I have also written a $ctrl.save() which allows the user to update their preferences and save it which works fine.
Now i have a reset button with $ctrl.cancelSettings().here i want the user to be able to change few preferences and if he decides to revert it before saving it the table should be set with the preferences how it was when loaded. Need some help on this part.
i cannot use forms here because of some other challenges.
HTML
<tbody>
<tr data-ng-repeat="app in $ctrl.notificationSettings" class="content-box">
<td data-ng-bind="app.appName"></td>
<td><ng-checkbox data-checked="app.email" rounded="true"></ng-checkbox></td>
<td><ng-checkbox data-checked="app.sms" rounded="true"></ng-checkbox></td>
</tr>
</tbody>
</table>
<div class="content-box">
<button class="ng-button-primary" data-ng-click="$ctrl.saveSettings()">Save</button>
<button class="ng-button-secondary" data-ng-click="$ctrl.cancelSettings()">Reset</button>
</div>
JS
$ctrl.getNotificationSettings = function () {
var url = "http://localhost:3000/json/notification-settings.json";
rsicontext.getData(url).then(function (response) {
$ctrl.notificationSettings = response.data;
$ctrl.appName = response.data.appName;
$ctrl.emailNotification = response.data.email;
$ctrl.smsNotification = response.data.sms;
});
};
$ctrl.cancelSettings = function () {
console.log("cancel settings");
};
JSON format to list the data
[{
"appName":"Finance",
"email":true,
"sms":false
},
{
"appName":"Sports",
"email":true,
"sms":true
},
{
"appName":"Economics",
"email":false,
"sms":false
},
{
"appName":"Health",
"email":false,
"sms":true
}]

what about the use of angular.copy to make a deep copy of the original object?
$ctrl.getNotificationSettings = function () {
var url = "http://localhost:3000/json/notification-settings.json";
rsicontext.getData(url).then(function (response) {
$ctrl.notificationSettings = response.data;
$ctrl.appName = response.data.appName;
$ctrl.emailNotification = response.data.email;
$ctrl.smsNotification = response.data.sms;
$scope.origData = angular.copy(response.data);
});
};
$ctrl.cancelSettings = function () {
$ctrl.notificationSettings = $scope.origData;
$ctrl.appName = $scope.origData.appName;
$ctrl.emailNotification = $scope.origData.email;
$ctrl.smsNotification = $scope.origData.sms;
};

I think there's 2 ways to solve your problem:
After retrieving data store it in temporary placeholder, and if user executes $ctrl.cancelSettings set form data to that of placeholder.eg:
$ctrl.getNotificationSettings = function () {
var url = "http://localhost:3000/json/notification-settings.json";
rsicontext.getData(url).then(function (response) {
$ctrl.placeholder = {};
$ctrl.notificationSettings = response.data;
$ctrl.placeholder.notificationSettings = response.data;
$ctrl.appName = response.data.appName;
$ctrl.placeholder.appName = response.data.appName;
$ctrl.emailNotification = response.data.email;
$ctrl.placeholder.emailNotification = response.data.email;
$ctrl.smsNotification = response.data.sms;
$ctrl.placeholder.smsNotification = response.data.sms;
});
};
$ctrl.cancelSettings = function () {
$ctrl.notificationSettings = $ctrl.placeholder.notificationSettings;
$ctrl.appName = $ctrl.placeholder.appName;
$ctrl.emailNotification = $ctrl.placeholder.emailNotification;
$ctrl.smsNotification = $ctrl.placeholder.smsNotification;
};
Or another solution would be just repeat the first function call in cancel operation:
$ctrl.cancelSettings = function () {
var url = "http://localhost:3000/json/notification-settings.json";
rsicontext.getData(url).then(function (response) {
$ctrl.notificationSettings = response.data;
$ctrl.appName = response.data.appName;
$ctrl.emailNotification = response.data.email;
$ctrl.smsNotification = response.data.sms;
});
};

Related

JQuery cloned element

I am stuck on this problem. I am coding a task platform app. Whenever I try to save, the task clones itself. After each "Save Changes," there are more and more clones. I have rewritten the code so many times. But still, I am not successful. Please help me to find the error.
$("#taskSave").click(() => {
const task = {
id: Date.now(),
imageUrl: $("#imageInput").val(),
title: $("#titleInput").val(),
description: $("#descriptionInput").val(),
type: $("#typeInput").val(),
};
$("#overlay").hide();
todos.push(task);
saveStorage(todos);
// reset input values
$("#imageInput").val("");
$("#titleInput").val("");
$("#descriptionInput").val("");
$("#typeInput").val("");
});
function saveStorage(todos) {
localStorage.setItem("todos", JSON.stringify(todos));
display(todos);
};
function display(todos) {
$("#taskBoard").innerHTML = "";
// .html("");
todos.forEach(item => {
let c = document.createElement("div");
c.setAttribute("class", "card");
c.setAttribute('id', item.id);
c.innerHTML = `
<div class="cardTop">
<div class="binContainer">
<div class="binImage"></div>
</div>
</div>
<img src="${item.imageUrl}" alt="task image">
<h2>${item.title}<h2>
<p>${item.description}</p>
<div class="cardType">${item.type}</div>
`;
$("#taskBoard").append(c);
// end
});
};
I've created a minimal working example, and the problem is in the cleanup of the HTML. You cannot use innerHTML on the JQuery object, or you use its html function or you need to retrieve the javascript object with $("#taskBoard")[0].
// You can use:
$("#taskBoard").html("");
// or
// document.getElementById("taskBoard").innerHTML = "";
// or
// $("#taskBoard")[0].innerHTML = "";
// But not:
// $("#taskBoard").innerHTML = "";
The working example here on JSFiddle (on SO dont work localStorage)
let todos = [];
$("#taskSave").click(() => {
const task = {
id: Date.now()
};
todos.push(task);
saveStorage(todos);
});
function saveStorage(todos) {
localStorage.setItem("todos", JSON.stringify(todos));
display(todos);
console.log(todos);
};
function display(todos) {
$("#taskBoard").html("");
// or
// document.getElementById("taskBoard").innerHTML = "";
// or
// $("#taskBoard")[0].innerHTML = "";
// But not
// $("#taskBoard").innerHTML = "";
todos.forEach(item => {
let c = document.createElement("div");
c.innerHTML = `
<p>${item.id}</p>
`;
$("#taskBoard").append(c);
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="taskSave">
SAVE
</button>
<div id="taskBoard">
</div>

How to call a custom JS file in Odoo 8?

I have a model called student. I also have form view, tree view for the student model. What I want to do is call my custom javascript file only when the form view of the student model is loaded. Is it possible? How to achieve this? Thanks.
What I tried is .....
openerp.student= function (instance) {
instance.web.FormView.include({
load_form: function(data) {
var self = this;
if (data.model === "student") {
altert('HELLO');
console.log('BLAH BLAH');
}
return this._super(data);
},
});
};
You can override the load_form method of FormView.
openerp.module_name= function (instance) {
instance.web.FormView.include({
load_form: function(data) {
var self = this;
if (data.model === "student") {
// Your custom code
}
return this._super(data);
},
});
};
To add the above code check this link inherit-or-override-js
It is possible to add a new view mode by extending FormFiew as Odoo did with account_move_line_quickadd.
openerp.your_module_name = function (instance) {
var _t = instance.web._t,
_lt = instance.web._lt;
var QWeb = instance.web.qweb;
instance.web.your_module_name = instance.web.your_module_name || {};
instance.web.views.add('student_form', 'instance.web.StudentFormView');
instance.web.StudentFormView = instance.web.FormView.extend({
load_form: function(data) {
var self = this;
// Add your custom code here
return this._super(data);
},
});
};
You just need to add the new mode to window action.
<record id="student_action" model="ir.actions.act_window">
<field name="name">student.action</field>
<field name="res_model">student</field>
<field name="view_mode">student_form,tree</field>
...

How to pass a list of a picklist component via AJAX to my Java controller in AngularJS?

Project: jsp + AngularJS
I have a modal, where I already pass some info to my Java controller via POST (ajax), it works fine.
But, I inserted a new component and I do not know how to receive my selected list of the picklist component, check image to understand:
For example, I have there fields I pass via POST to my java controller and works fine:
$scope.cadastraCertificado = function() {
$http.post('/boxmlV2/cadastrocertificado/salvaCertificado', {
urlCertificado : $scope.certificadoIncluirAlterar.urlCertificado,
dataValidadeCertificado : $scope.certificadoIncluirAlterar.dataValidadeCertificado.toString(),
senhaCertificado : $scope.certificadoIncluirAlterar.senhaCertificado
//picklist????????
}).then(function(response) {
$scope.sucesso();
}, function(response) {
});
};
But I do not know how to receive data from my list selected in the picklist component, the ones from the right side.
How can I do that?
My picklist:
<div class="form-group">
<label class="control-label col-md-3">Empresas:</label>
<div class="col-md-9">
<select ng-model="corvo" multiple="multiple" class="multi-select" id="my_multi_select1" name="my_multi_select1[]">
<option ng-repeat="c in clientes" value="{{c.idCliente}}" ng-click="atribuirUm($index, c)">{{c.razaoSocial}}</option>
<option selected ng-repeat="c2 in clientes2" value="{{c2.idCliente}}" ng-click="limparUm($index, c2)">{{c2.razaoSocial}}</option>
</select>
</div>
</div>
$scope.corvo will contain an array with the IDs (the values) of the selected elements, so you can just send that array:
$http.post('/boxmlV2/cadastrocertificado/salvaCertificado', {
urlCertificado : $scope.certificadoIncluirAlterar.urlCertificado,
dataValidadeCertificado : $scope.certificadoIncluirAlterar.dataValidadeCertificado.toString(),
senhaCertificado : $scope.certificadoIncluirAlterar.senhaCertificado,
corvo: $scope.corvo
}).then(function(response) {
$scope.sucesso();
}, function(response) {
});
I assume you are sending JSON data, otherwise you have to serialize it to a string, for example using $scope.corvo.join(',').
This is how my js looks like after working ok:
BoxApp.controller("CadastroCertificadoController", function($scope, $http) {
$scope.clientes = {};
$scope.listaEmpresas = [];
$scope.iniciar = function() {
$http.get('/boxmlV2/cadastrocertificado').success(function(response) {
$scope.clientes = response;
});
};
$scope.iniciar();
/**
* Trabalhando o componente picklist
*/
$scope.clientes2 = [];
$scope.atribuirUm = function(index, c) {
var cliente = {};
cliente.idCliente = c.idCliente;
cliente.razaoSocial = c.razaoSocial;
$scope.clientes2.push(cliente);
$scope.clientes.splice(index, 1);
}
$scope.limparUm = function(index, c2) {
$scope.clientes2.splice(index, 1);
$scope.clientes.push(c2);
}
/**
* Trecho para validar o form ao submeter.
*/
$scope.submitted = false;
$scope.submitForm = function(form, clientes2) {
$scope.listaEmpresas = $scope.clientes2;
$scope.submitted = true;
if (form.$valid) {
$scope.cadastraCertificado();
}
};
/**
* Requisição POST (ajax)
*/
$scope.cadastraCertificado = function() {
var dados = {
urlCertificado : $scope.certificadoIncluirAlterar.urlCertificado,
strDataValidadeCertificado : $scope.certificadoIncluirAlterar.strDataValidadeCertificado.toString(),
senhaCertificado : $scope.certificadoIncluirAlterar.senhaCertificado,
listaEmpresas : $scope.listaEmpresas
};
$http.post('/boxmlV2/cadastrocertificado/salvarCertificado', dados).then(function(response) {
}, function(response) {
$scope.sucesso();
});
};
$scope.sucesso = function() {
$scope.closeMyPopup();
$scope.iniciar();
};
$scope.closeMyPopup = function() {
$(myModal_autocomplete).modal('hide');
};
});

sqlite selected data not showing to ng-repeat

I am calling the data from listItems.push(res.rows.item(i).name); to a list by ng-repeat. so that i got a list of names that are present in SQLite.
This is my controllers.js
$scope.createList = function () {
var value1 = document.getElementById("List").value;
alert(value1);
var db = $cordovaSQLite.openDB({ name: "Bd_DB.db" });
var query = "INSERT INTO List (name) VALUES (?)";
$cordovaSQLite.execute(db, query, [value1]).then(function (res) {
console.log("insertId: " + res.insertId);
}, function (err) {
alert(err);
console.error(err);
});
$scope.getAllLists();
};
$scope.getAllLists = function () {
var listItems= [];
var query = "SELECT * FROM List";
$cordovaSQLite.execute($cordovaSQLite.openDB({ name: "Bd_DB.db" }), query).then(function (res) {
if (res.rows.item(0).name !="") {
for (var i = 0; i < res.rows.length; i++) {
listItems.push(res.rows.item(i).name);
}
}
});
}
I have tried , and but it is not showing any kind of list. i don't know, what i m doing wrong. please tell me the right code. Thanks
This is my Html:
<div class="bar bar-header">
<button class="button icon-left ion-chevron-left button-clear button-dark" ng-click="closeModal()" ></button>
<h1 class="title">Your List</h1>
<button class="button" ng-click="createListPopup()"> Create List</button>
</div>
My ToDo List
<ion-content>
<div ng-repeat= "name in listItems">
{{item.name}}
</div>
</ion-content>
sqlite transaction is synchronous, so in the create list, you have to call the getList in the success callback of the execute:
like:
$scope.createList = function () {
var value1 = document.getElementById("List").value;
alert(value1);
var db = $cordovaSQLite.openDB({ name: "Bd_DB.db" });
var query = "INSERT INTO List (name) VALUES (?)";
$cordovaSQLite.execute(db, query, [value1]).then(function (res) {
console.log("insertId: " + res.insertId);
$scope.getAllLists();
}, function (err) {
alert(err);
console.error(err);
});
};
Also, in the getAllLists, the function will end regardless of the status of the .execute, so you have to bind to a variable which be set inside the success callback.
$scope.listItems= [];
$scope.getAllLists = function () {
var query = "SELECT * FROM List";
$cordovaSQLite.execute($cordovaSQLite.openDB({ name: "Bd_DB.db" }), query).then(function (res) {
$scope.listItems= [];
if (res.rows.item(0).name !="") {
for (var i = 0; i < res.rows.length; i++) {
listItems.push(res.rows.item(i).name);
}
$scope.$apply();
}
}
Finally, you have to made $scope.$apply() to reflect the result to the view.
Try changing var listItems= [] to a scope variable
$scope.listItems = [];
....
$scope.listItems.push({name:'item 1'})
and then in your view:
<ion-content>
<div ng-repeat= "item in listItems">
{{item.name}}
</div>
</ion-content>

Angular, ng-grid and dynamically populating the grid

I am trying to populate an ng-grid after an AJAX call is returned. The user presses the button to perform a query, and the result is intended to be shown in a grid.
My html is:
<div class="gridStyle" ng-grid="gridOptions" ></div>
And my js is:
app.queryCallback = function(graph) {
var results = graph.toJSON();
var columns = [ns.gtry("hasRank"), ns.gtry("score"), ns.gtry("ks_up"), ns.gtry("ks_down")];
var names = ["Has Rank", "Score", "up", "down"];
$scope.queryData = [];
$.each(results, function(key, values) {
var row = {};
$.each(values, function(uri, dict){
$.each(columns, function(i, column){
if (column == uri) {
row[names[i]] = dict[0]['value'];
}
});
});
$scope.queryData.push(row);
});
$scope.gridOptions = {data : 'queryData'};
$scope.$apply();
}
and my controller is set up as follow:
goiapp.controller('goip', function ($scope) {
var app = this;
However, the grid isn't shown, and with the chrome debugger, I have verified that app.queryData has the correct objects.

Categories