ng-click not working after first click (embedded directives) - javascript

I'm having issues with a button and ng-click. I have an input and a button with and ng-click that when click generates 3 random words. I display this words in a div generated by a directive.
The problem I'm having is that when I click the button the first time the code runs perfectly, but when I click again, the button does nothing, I had to implement a clear button that clears the $scopes and then the generate button works again.
This is the code for my button:
<button class="btn btn-default" type="button" ng-click='generateRandom()'>Generate</button>
Here is the code for the directive:
<div jz-tabs camel='camel' snake='snake' kebab='kebab'></div>
The $scope.generateRandom():
$scope.generateRandom = function() {
var temp = '';
Words.getWords($scope.number)
.then(function(response) {
console.log(response);
response.data.forEach(function(e) {
console.log(e);
temp += ' ' + e.word;
});
$scope.camel = lodash.camelCase(temp);
$scope.kebab = lodash.kebabCase(temp);
$scope.snake = lodash.snakeCase(temp);
});
};
I tried clearing the $scopes inside of the function but it looks like after the first ng-click, the function isn't even been called. Does having embedded directives affect ng-clicks?
Any help with this? I don't want to click "clear" every time I want to generate words, I want them to be able to click generate and get random words every time.
Thank you in advance!
UPDATE: Here is a plnkr of the problem: http://plnkr.co/edit/qGB1VjsIJgBzWKl8tXMt?p=preview

I fixed the problem, I had this two functions:
$scope.generateRandom = function() {
var temp = '';
Words.getWords($scope.number)
.then(function(response) {
for (var i = 0; i < response.data.length; i++) {
temp += ' ' + response.data[i].word
}
$scope.camel = temp;
$scope.kebab = temp;
$scope.snake = temp;
});
};
$scope.clear = function() {
$scope.camel = '';
$scope.kebab = '';
$scope.snake = '';
};
All I had to do was add $scope.clear() at the end of the $scope.generateRandom function and it does the trick.

Related

element.onclick not doesn't call function when element is clicked

I am building a Modal dynamically. I want to make some buttons in this modal to open a SubModal. The buttons show up in html, but clicking these buttons does nothing.
Here is my code.
const subtaskList = document.getElementById('subtaskList');
for (const subtaskIndex in task.subtasks) {
const subtaskButton = document.createElement('button');
subtaskButton.classList.add('taskModalSubtaskButton');
subtaskButton.onclick = () => {
openSubTaskModal(task.subtasks[subtaskIndex], task);
}
subtaskButton.innerText = task.subtasks[subtaskIndex].name;
subtaskList.appendChild(subtaskButton);
subtaskList.innerHTML += '<br>';
}
While troubleshooting I made an array to hold the buttons and used console.log() to see its elements. They all had the onclick function. I've clicked the buttons from the dev console by getting their class name and nothing, so I know it's not a display issue. I feel like I am misunderstanding something and any help would be appreciated.
The problem is subtaskList.innerHTML += '<br>'; it is good idea to use subtaskList.appendChild(document.createElement("br")); instead.
Here is working snippet:
function doSomething(url) {
alert(url);
}
const subtaskList = document.getElementById('subtaskList');
for (var i = 0; i < 3; i++) {
const subtaskButton = document.createElement('button');
subtaskButton.classList.add('taskModalSubtaskButton');
subtaskButton.innerText = "name" + i;
subtaskButton.onclick = (function (url) {
return function () {
doSomething(url);
};
})("URL #" + i)
subtaskList.appendChild(subtaskButton);
subtaskList.appendChild(document.createElement("br"));
}
<div id="subtaskList"></div>
Also I change a bit onclick function to send correspond index to doSomething function

pass click event between two page by localStorage

I want to take a click event from 2nd page . 1st page have a link for 2nd page, there have a button when click the button it add a HTML row on 1st page. I am trying to use localStorage for passing data. My code don't work, take a look below:
1st Page.html
HTML
<div id="content">
</div>
JS
var output = document.getElementById('content');
addEvent(window, 'storage', function (event) {
if (event.key == 'StorageName') {
output.innerHTML = event.newValue;
}
});
2nd Page.html
HTML
<input id="data" type="button" value="+" onclick="addRow()">
JS
addEvent(dataInput, 'keyup', function () {
localStorage.setItem('StorageName', this.value);
});
var dataInput = dataInput = document.getElementById('data');
object.onclick = function(){
addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
};
You haven't defined your addRow() function properly. A function's name is defined with the keyword function, not inside of the function body. Your code:
object.onclick = function(){
addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
};
Should be changed to:
function addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
object.onclick = addRow;
I agree with skyline3000's answer the addRow() should be defined. Also there are a few other things that could/should change:
define dataInput before attaching an event to it
object.onclick should be dataInput.onclick since thats the element being clicked. (is click event what you really want? maybe onkeyup?)
when you set the localStorage you want to set the function definition being passed to Page 1 which appears to be addRow(). Simply remove the parenthesis to pass just the definition.(Should also be defined before using)
If you want to just pass the function you shouldn't set the onclick event on Page 2. What you should probably do is record how many times you want it to run when you go to Page 1.
You dont need to pass the function everytime if it isnt changing; Just set it once and record the number of times it was clicked.
page 1 can catch the load event and the check localStorage for the function definition and number of times it was run. Then it can loop and perform the function.
the code you have doesn't add a link back to page 2 if thats what you are looking for but you can add that into the addrow function when you know the file name and path.
Page 1
var output = document.getElementById('content');
addEvent(window, 'load', function (event) {
if (localStorage.getItem('StorageName') && localStorage.getItem('rowsToAdd')) {
for(var i = 0; i > rowsToAdd;i++){
var addNewRow = localStorage.getItem('StorageName');
addNewRow();
}
}
});
Page 2
var dataInput = document.getElementById('data');
function addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
};
localStorage.setItem('StorageName', addRow);
dataInput.onclick = function() {
if(localStorage.getItem('rowsToAdd')){
localStorage.setItem('rowsToAdd', localStorage.getItem('rowsToAdd') + 1);
}else{
localStorage.setItem('rowsToAdd',1);
}
}
I didn't test this code so it may not work copy+pasted but something pretty close hopefully.
I also answered this with the best understanding of what you wanted that I could manage but I dont fully see the desired result of what you seemed to be doing.

Button not working in multi-page application

I have created 2 buttons. The second button should go to NewFile.html but it isn't working. my index.html main file consist of div tag inside it created 2 buttons and with id ForNext for one of the button.
main.js
var pagesHistory = [];
var currentPage = {};
var path = "";
function wlCommonInit(){
$('#ForDeviceProp').click(deviceProp);
$('#ForNext').click(nextMethod);
}
function nextMethod() {
$("#ForNext").load(path + "pages/NewFile.html", function(){
$.getScript(path + "js/NewPage.js", function() {
if (currentPage.init) {
currentPage.init();
}
});
});
}
Newpage.js
currentPage = {};
currentPage.init = function(){
WL.Logger.debug("NewFile :: init");
};
There are all sort of issues, but the main ones are the following:
In nextMethod() You are trying to load NewFile.html into the ID of your button. That won't work: $("#ForNext").load("pages/NewFile.html", function(){
It needs to be loaded into the pagePort DIV. Replace "ForNext" with "pagePort".
In bba= WL.Client.getEnvironmen();, you are missing the "t" in ".getEnvironment".

Associate buttons and click actions in a loop

I am trying to associate several click actions to several buttons, in jQuery. I am using a for loop to browse all the buttons.
I tried something like that :
var realThis = $(this);
// ...
for (var i = 0; i < buttons.length; i++) {
if (typeof(buttons[i].callback) !== 'undefined')
$('#' + buttons[i].id).click(function(){
buttons[i].callback(realThis.getFormValues());
});
}
I got a warning from my editing software :
Mutable variable is accessible from closure
I tried several things without any success.
Any help here ?
I would change the structure of your HTML so that you know which handler will be attached. Data attributes might help you:
<button id="button-1" data-button-id="1" class="button-action">
Do action 1
</button>
<button id="button-2" data-button-id="2" class="button-action">
Do action 2
</button>
You can then attach your handlers to all buttons, and work out which function you want to call on click, instead of in advance:
$('.button-action').on('click', function (e) {
// get the button index from the data attribute
var buttonId = $(e.currentTarget).data('buttonId');
// if there's a callback then execute it
if (buttons[buttonId].callback) {
buttons[buttonId].callback(realThis.getFormValues());
}
});
Finally found an answer to my problem :
for(var i = 0; i < buttons.length; i++)
{
(function()
{
if(buttons[i].callback)
{
var callbackTemp = buttons[i].callback;
$('#' + buttons[i].id).click(function(){ callbackTemp(realThis.getFormValues()); });
}
})();
}
Thanks for you help ;)

How to trigger an event after clicking two different button in Javascript

I was wondering how I can trigger an event after two different buttons being clicked. Specifically I have some buttons with different ids and I want when I click two specific buttons from them to trigger an event. I thought that this can be happen If I call some function in the first on click event and inside this function I can call another function if the second button being clicked. It does not seem to work, so I need your help. (If anyone needs more code please comment to upload the whole code)
function someKindOfFunction(){
//there is some other code here
var ob = document.getElementById(idTable[0]);
var ob1 = document.getElementById(idTable[1]);
var ob2 = document.getElementById(idTable[2]);
var ob3 = document.getElementById(idTable[3]);
ob.addEventListener("click",function() {onCl1(idTable[0],idTable)});
ob1.addEventListener("click",function() {onCl1(idTable[1],idTable)});
ob2.addEventListener("click",function() {onCl1(idTable[2],idTable)});
ob3.addEventListener("click",function() {onCl1(idTable[3],idTable)});
}
function onCl1(id1,idTable){
var obj1 = document.getElementById(id1);
obj1.disabled=true;
var obj2,v,obj3,obj4;
v=0;
var temp = ["0","0","0"];
for(var i =0 ; i<4 ; i++){
if( id1 != idTable[i]){
temp[v] = idTable[i];
v=v+1;
}
}
ob=document.getElementById(temp[0]);
ob1=document.getElementById(temp[1]);
ob2=document.getElementById(temp[2]);
ob.addEventListener("click",function() {onCl2(id1,temp[0])});
ob1.addEventListener("click",function() {onCl2(id1,temp[1])});
ob2.addEventListener("click",function() {onCl2(id1,temp[2])});
}
function onCl2(id1,id2){
//some kind of actions
alert("it wokrs");
}
Just pass some sort of value whenever the button you want is clicked. For instance:
ob.addEventListener("click",function() {onCl1(1)});
ob1.addEventListener("click",function() {onCl1(1)});
var i;
function onCl1(value){
i += value;
if(i == 2){
//do this
}
}
So basically once these two buttons are clicked the value will equal 2 and trigger whatever you want.

Categories

Resources