Is JQuery breaking my functionality? - javascript

I am making an app, the user can either select an item or use their camera to get the qr code which translates into an item's ID.
The problem is that I think some JQuery is messing with my scope from working properly.
I have to get the QR code by listening to an innerHtml change, once it changes (DOMSubtreeModified) the following occurs.
var index = 0;
$('#result').one('DOMSubtreeModified', function(e) {
var code = "";
if (e.target.innerHTML.length > 0) {
code = e.target.innerHTML;
$scope.ToRun(code);
}
});
$scope.ToRun = function(code) {
for (i = 0; i < $scope.plantList.length; i++) {
if ($scope.plantList[i].plantcode == code) {
index = i;
break;
}
}
$scope.currentPlant = $scope.plantList[index];
$scope.plantDetails = false;
$scope.searchDetails = true;
}
For some reason the following does not have any effect on my ng-classes. As when an item is selected I hide the input dialogs, and show the result one.
$scope.plantDetails = false;
$scope.searchDetails = true;
But when a user selects the item manually it works just perfectly. (the items have an ng-click on it)
$scope.viewPlant = function(plant) {
$scope.currentPlant = plant
$scope.plantDetails = false;
$scope.searchDetails = true;
};
And the above works fine, with the ng-click. So why won't my new function that listens for an innerHtml change work?
HTML snippet
<div ng-class="{ 'hidden': searchDetails }">
<!-- CHOOSE INPUT TYPE -->
<div class="form-group" style="margin-bottom:0px">
<div class="btn-group btn-group-justified">
<div class="btn-group">
<button type="button" class="btn btn-default" ng-click="digits = false; qr = true">Plant Code</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-default" ng-click="digits = true; qr = false">QR Code</button>
</div>
</div>
</div>
<br />
<!-- QR CODE INPUT -->
<div ng-class="{ 'hidden': qr }">
<img id="blah" src="./images/placeholder.png" />
<span class="btn btn-default btn-file">
<i class="glyphicon glyphicon-camera"></i>
<input type="file" onchange="readURL(this);handleFiles(this.files)">
</span>
<div id="result">xxxxxx</div>
<canvas id="qr-canvas" width="800" height="600"></canvas>
</div>
<!-- MANUAL SELECTION INPUT -->
<div ng-class="{ 'hidden': digits }">
<input ng-model="search.$" style="width:100%; font-size:30px; text-align:center" placeholder="Plant Code" />
<div style="overflow: auto; max-height:250px">
<table class="table table-striped" style="background-color:lightblue">
<tr ng-repeat="plant in plantList | filter:search" ng-click="viewPlant(plant)" style="cursor:pointer">
<th>{{plant.name}}</th>
<th>{{plant.plantcode}}</th>
</tr>
</table>
</div>
</div>
<div>
</div>
</div>
<div ng-class="{ 'hidden': plantDetails }">
// results - this should appear when one of the above is entered.
// works for manual selection, but not qr code
</div>
Just confused on why my QR input will not fire off the change-class options to hide the searchDetails div and show the plantDetails div
EDIT: Doing a small test, it seems that my class variables are indeed not updating at all. I just put the values at the bottom of my page and they do not update when hitting the block of:
$scope.plantDetails = false;
$scope.searchDetails = true;

You need to let Angular know about the change. Add this at the end of your method and let me know if it works.
$scope.$apply();

Related

Dynamically added <input> not being rendered

I have a string which holds a form that I want to dynamically render.
When the user clicks "Add Step", my template string is added to a list and rendered with an ngFor. The problem is that the input doesn't render, only the <h3> tag.
Before button click:
After - no input is rendered on screen or in the html:
ts:
scenarioTemplate = `
<div id="content">
<h3>Name</h3>
<input name="{{i}}" [ngModel]="i">
</div>`;
steps = [];
addScenarioStep() {
this.steps.push(this.scenarioTemplate);
}
html:
<form #myForm="ngForm">
<fieldset ngModelGroup="inputs" #inputs="ngModelGroup">
<ng-container *ngFor="let step of steps; let i = index">
<div [innerHTML]=step attr.stepId="{{i}}"></div>
</ng-container>
</fieldset>
</form>
<button id="addStepBtn" type="button" class="btn btn-light" (click)="addScenarioStep()">Add Scenario Step +</button>
Put that whole thing
<div id="content">
<h3>Name</h3>
<input name="{{i}}" [ngModel]="i">
</div>
in the template, not the TS.
Don't mutate the array. Instead of
this.steps.push(newElem);
do
this.steps = [...this.steps, newElem];

Second execution follows href

With a list of products, and once a 'remove from wishlist' button is clicked, it then removes that product from said product list, along with an AJAX request to the back-end for it to be removed via SQL.
The first click works, the jQuery executes and the product is then removed. The second click on the same type of button for any product, then loads the href instead of executing the jQuery, it's meant to execute the jQuery.
I've tried calling it as a static function from the anchor onclick="return removeFromWishlist();"
Have also tried executing the jQuery on the anchor link click via the jQuery event instead of the button tag itself.
jQuery('.button-wishlist').on('click', function (index) {
event.preventDefault();
// Calls the AJAX to remove it from the back-end via SQL etc
// The response is JSON within the following call
removeProductAjax(this);
console.log('removing product from the wishlist');
// Get the cell position of the product to remove from the wishlist
var position = jQuery(this).parent().parent().parent().data('cell');
var html = [];
var cells = 0;
jQuery('.wishlist_container .col-md-4').each (function () {
//
if (jQuery(this).data('cell') == position) {
cells++;
}
else if (jQuery(this).data('cell') !== undefined) {
html.push(jQuery(this).html());
cells++;
}
});
var upto = 0;
jQuery('.product-row').each (function () {
var self = this;
// Repopulate all the product lists excluding the one removed
jQuery(self).children().each (function () {
jQuery(this).html(html[upto]);
upto++;
});
});
// Then clear everything from upto and onwards!
console.log('cells: ' + cells);
console.log('upto: ' + upto);
// let's change from array to 'standard' counting
upto--;
// Remove the last element!
jQuery('.product-row').find('[data-cell=' + upto + ']').remove();
// Check for any empty rows
jQuery('.product-row').each (function () {
if (jQuery(this).children().length == 0) {
jQuery(this).remove();
}
});
});
The HTML is basically:
<div class="row product-row">
<div class="row product-row"><div class="col-md-4" data-cell="0">
<h1>product 1</h1>
<a href="./page.php?page=cart&unwish=660986" data-index="660986" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
<div class="col-md-4" data-cell="1">
<h1>product 2</h1>
<a href="./page.php?page=cart&unwish=661086" data-index="661086" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
<div class="col-md-4" data-cell="2">
<h1>product 3</h1>
<a href="./page.php?page=cart&unwish=661067" data-index="661067" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
</div>
I'm expecting it to execute the jQuery each time the "remove from wishlist" button is clicked, no matter what product, no matter what order. So, you can unwish many products, one after the other using AJAX / jQuery.
Follow all my comments under your Question...
And I think this is all the code you need.
PHP (I used i.e: ../removeProduct.php?id=) should respond with some JSON like:
// PHP does here some DB deletions or fails.
// Send back to AJAX the deleted item ID (or null)
// and some (error?) message
echo json_encode(['id' => $id, 'message' => $message]);
exit;
// No more PHP here. We exit.
// jQuery will collect that JSON response as `res`
jQuery(function($) {
function removeProductAjax(id) {
$.get("../removeProduct.php?id=" + id, 'json').always(function(res) {
if (res.statusText === 'error') { // General error (path invalid or something...)
return alert(`Error: Cannot remove product ID: ${id}`); // and exit function
}
if (!res.id) { // Something happened
return alert(res.message); // Alert PHP's error message and exit function.
}
// All OK. Remove item from products
$(".product-row").find(`[data-id="${res.id}"]`).remove();
});
}
$('.product-row').on('click', '.product-remove', function(ev) {
ev.preventDefault();
removeProductAjax($(this).data('id'));
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div class="row product-row">
<div class="col-md-4" data-id="660986">
<h3>product 1</h3>
<button type="button" class="btn product-remove" data-id="660986">Remove from Wishlist</button>
</div>
<div class="col-md-4" data-id="661086">
<h3>product 2</h3>
<button type="button" class="btn product-remove" data-id="661086">Remove from Wishlist</button>
</div>
<div class="col-md-4" data-id="661067">
<h3>product 3</h3>
<button type="button" class="btn product-remove" data-id="661067">Remove from Wishlist</button>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

I can´t remove the last item of array

I can remove any item of array unless the last one. I also use angularjs to show information in the view. I don´t know what is happening with the last item of this array. Please, anyone can help me?
Here is HTML:
<div class="row">
<div class="col-md-12">
<h4><strong>Documento {{index + 1}} de {{documentos.length}}:</strong> {{documentos[index].nome}}</h4>
<iframe style="background: #ccc;" ng-show="exibirPreview" frameborder="0" ng-src="{{versaoLink}}" width="100%" height="300px"></iframe>
<div class="alert alert-warning" ng-hide="exibirPreview">
#Html.Raw(Resources.Dialog.SignDocuments.TypeDocumentCanNotPreDisplayed)
</div>
<hr />
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<button class="btn btn-default" type="button" ng-click="RemoveDoc(index)"><i class="fa fa-fw fa-times"></i> #Resources.Common.RemoveDocList</button>
</div>
</div>
</div>
Here is js/angularjs
$scope.documentos = [
{nome:"document1", chave: "8F65579E3737706F", extensao:".pdf"},
{nome:"document2", chave: "8F65579E3730007F", extensao:".pdf"},
{nome:"document3", chave: "8545579E3737706F", extensao:".pdf"},
{nome:"document4", chave: "8555579E3730007F", extensao:".pdf"}
]
$scope.ViewLink = function () {
var versao = $scope.documentos[$scope.index];
$scope.exibirPreview = versao.extensao == ".pdf" || versao.extensao == ".txt";
if (!$scope.exibirPreview) {
$scope.versaoLink = '';
} else {
$scope.versaoLink = '/Documento/VersaoView?chave=' + versao.chave;
}
};
$scope.ViewLink();
$scope.RemoveDoc = function (index) {
$scope.documentos.splice(index, 1);
$scope.ViewLink();
};
Or Plunker
In your HTML you are preventing the deletion of the last element:
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<!-- -->
</div>
documentos.length > 1 means "hide when it reaches one item in the array".
It should be documentos.length == 0.
It's either this or your index value starts from 1 and not from 0.
The simplest solution would be to change your remove function to take in the document instead of the index. Try this:
$scope.RemoveDoc = function(document) {
var index = $scope.documents.indexOf(document);
$scope.documents.splice(index, 1);
}
in view:
<button class="btn" type="button" ng-click="RemoveDoc(document)">Delete</button>

ng-template not getting refreshed on clicking the button

I have the following controller:
function _deleteServiceInstance(serviceInstanceId) {
self.hasServerErrors = false;
self.serverErrors = [];
var flag = 1;
if (confirm("Are you sure you want to delete the service instance in this environment region?")) {
for (var i = 0; i < self.serviceInstanceDeployments.length; i++) {
var obj = self.serviceInstanceDeployments[i];
if (obj.state === "ACTIVE")
flag = 0;
}
if (flag === 0)
{
self.hasServerErrors = true;
self.serverErrors = ["Please delete the active deployments before deleting the service instance"];
// $window.location.reload();
$scope.$apply();
return self.serverErrors;
};
}
}
The following is the HTML:
<a uib-popover-template="ctrl.deleteServiceInstanceTemplate" popover-title="Delete service instance"
popover-placement="auto bottom" popover-trigger="outsideClick">
<button type="button" class="btn btn-danger">
Delete
</button>
</a>
<script type="text/ng-template" id="deleteServiceInstance.html">
<div class="container-fluid">
<div class="row">
<form name="ctrl.delete.form" class="form-horizontal" novalidate>
<div class="form-group" ng-class="{'has-error' : ctrl.hasServerErrors}">
<label class="col-sm-12 control-label">Are you sure?
<button type="submit" class="btn btn-primary" ng-click="ctrl.deleteServiceInstance(ctrl.serviceInstance.id)"
ng-disabled="ctrl.purge.form.$invalid">Yes</button>
<span ng-show="ctrl.hasServerErrors" class="help-block" ng-repeat="serverError in ctrl.serverErrors">{{serverError}}</span>
</label>
</div>
</form>
</div>
</div>
</script>
Basically, there is a delete button which opens as a pop-up. It asks for confirmation if I am sure of deleting something. If I press yes, it checks if there are any deployments in active state. If there are, it shows an error. Now, the problem is, when I click on the delete button for the second time, it shows the same error even when I haven't pressed yes. It keeps on showing the same error until the page is refreshed.
Edit: I have declared the _deleteServiceInstance like this in my controller:
self.deleteServiceInstance = _deleteServiceInstance
You should clear the messages while clicking the delete button event, instead of yes button click event
<button type="button" ng-click="clearMessages" class="btn btn-danger">
Delete
</button>
Controller
function _clearMessages() {
self.hasServerErrors = false;
self.serverErrors = [];
}
self.clearMessages= _clearMessages

How to dynamically append templates to a page in Angular

So the situation is as follows:
I have an input bar where a user can search up a business name or add a person's name (and button to select either choice). Upon hitting enter I want to append a unique instance of a template (with the information entered by the user added). I have 2 templates I've created depending of if the user is searching for a business or a person.
One approach I've thought about is creating an object with the data and adding it with ng-repeat, however I can't seem to get the data loaded, and even then don't know how I can store reference to a template in my collection.
The other idea I've come across is adding a custom directive. But even then I've yet to see an example where someone keeps appending a new instance of a template with different data.
Here is the code so far:
payments.js:
angular.module('payment-App.payments',['ngAutocomplete'])
.controller('paymentController', function($scope, $templateRequest/*, $cookieStore*/) {
$scope.businessID;
$scope.address;
$scope.isBusiness = false;
$scope.payees = [];
$scope.newPayee = function () {
this.businessID = $scope.businessID;
this.address = $scope.address;
}
$scope.submit = function () {
var text = document.getElementById("businessID").value.split(",");
$scope.businessID = text[0];
$scope.address = text.slice(1).join("");
$scope.newPayee();
}
$scope.addPayee = function () {
$scope.submit();
$scope.payees.push(new $scope.newPayee());
console.log($scope.payees);
}
$scope.selectBusiness = function () {
//turns on autocomplete;
$scope.isBusiness = true;
}
$scope.selectPerson = function () {
//turns off autocomplete
$scope.isBusiness = false;
}
$scope.fillAddress = function () {
// body...
}
})
.directive("topbar", function(){
return {
restrict: "A",
templateUrl: 'templates/businessTemplate.html',
replace: true,
transclude: false,
scope: {
businessID: '=topbar'
}
}
})
payments.html
<h1>Payments</h1>
<section ng-controller="paymentController">
<div>
<div class="ui center aligned grid">
<div class="ui buttons">
<button class="ui button" ng-click="selectBusiness()">Business</button>
<button class="ui button arrow" ng-click="selectPerson()">Person</button>
</div>
<div class="ui input" ng-keypress="submit()">
<input id="businessID" type="text" ng-autocomplete ng-model="autocomplete">
</div>
<div class="submit">
<button class="ui button" id="submit" ng-click="addPayee()">
<i class="arrow right icon"></i>
</button>
</div>
</div>
<div class="search"></div>
<div class="payments" ng-controller="paymentController">
<li ng-repeat="newPayee in payees">{{payees}}</li>
</div>
<!-- <topbar></topbar> -->
</div>
(example template)
businessTemplate.html:
<div class="Business">
<div class="BusinessName" id="name">{{businessID}}</div>
<div class="Address" id="address">{{address}}</div>
<button class="ui icon button" id="hoverbox">
<i class="dollar icon"></i>
</button>
</div>
I ended up using a workaround with ng-repeat here. Still curious about the original question though.

Categories

Resources