Angularjs View Not Updating, View Flickers on Button Click - javascript

I have written the following HTML & AngularJS code to update the Tree on HTML Page (View) on the Click of a Button.
When the Button is clicked, the changes appear for a fraction of second and disappear. I am not able to find the reason for this. Could you please let me know how I can overcome this problem?
Below is the HTML and JS Code. This is working in the Snippet Editor, but not in the Browser.
var module = angular.module('myapp', []);
module.controller("TreeCtrl", function($scope) {
$scope.categories = [];
$scope.$apply($scope.addTreeToView = function() {
$scope.categories = [{
title: 'Computers1',
categories: [{
title: 'Laptops1',
categories: [{
title: 'Ultrabooks1'
}, {
title: 'Macbooks1'
}]
}, {
title: 'Desktops1'
}, {
title: 'Tablets1',
categories: [{
title: 'Apple1'
}, {
title: 'Android1'
}]
}]
}, {
title: 'Printers1',
categories: [{
title: 'HP1'
}, {
title: 'IBM1'
}]
}];
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tree Example</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="myapp">
<div class="col-sm-10 col-sm-offset-1" ng-controller="TreeCtrl">
<form action="#" method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group" id="div_submitComment">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-success btn-circle text-uppercase" type="submit" ng-click="addTreeToView()"><span class="glyphicon glyphicon-send" id="qazwsx"></span> Create Tree</button>
</div>
</div>
</form>
<div class="page-header">
<h3 class="reviews">Tree</h3>
</div>
<script type="text/ng-template" id="categoryTree">
{{ category.title }}
<ul ng-if="category.categories">
<li ng-repeat="category in category.categories" ng-include="'categoryTree'">
</li>
</ul>
</script>
<ul>
<li ng-repeat="category in categories" ng-include="'categoryTree'"></li>
</ul>
</div>
</div>
<script src="self.js"></script>
</body>

try removing type="submit" from the buttom

I was using Form element type of Bootstrap. This has an action attribute. I removed the action attribute. Code works fine after removing it
< form method = "post"
class = "form-horizontal"
id = "commentForm"
role = "form" >
< div class = "form-group"
id = "div_submitComment" >
< div class = "col-sm-offset-2 col-sm-10" >
< button class = "btn btn-success btn-circle text-uppercase"
type = "submit"
ng - click = "addTreeToView()" > < span class = "glyphicon glyphicon-send"
id = "qazwsx" > < /span> Create Tree</button >
< /div>
</div >
< /form>

Because your html will be reloaded after you do "submit" action.So you have to replace "type="submit" by type="button" and disable "auto submit".

Related

How can I check how many elements are inside one field?

I have a piece of code in my HTML:
<div class="all-homes">
<div class="home">RED</div>
<div class="home">WHITE</div>
<div class="home">GREEEN</div>
<div class="home">BLUE</div>
</div>
I need to remove home from the list only if in the class of all-homes there are more than 1 home. Otherwise there should be a warning message saying that you can't remove home because there is just 1 home in the list. Would that be possible?
I was try:
<script>
function myFunction() {
if (document.getElementsByClassName("all-homes") "how to gete the right informatuion here" ) {
event.run();
}else {
event.preventDefault(); // prevent form submit
swal({
title: "Remove Home",
text: " text",
icon: "warning",
});
}
}
</script>
My remove Button:
<p>{{home_at_homes_pk}}</p> //this is the home list
<form method='post' action="{% url 'home_at_homes_delete' home_at_homes_pk=home_at_homes_slug%}">
{% csrf_token %}
<button type="submit" onclick="myFunction()" id="remove-location" class="txt-button alert icon-link" style="margin-top: 0rem;">
<span class="icon">
<i class="fas fa-trash-alt"></i>
</span>
Remove Home
</button>
</form>
update from comment:
I want to remove the whole elements until one is left
Thank you very much
function myFunction() {
var all = document.getElementsByClassName("all-homes")[0];
while (all.children.length > 1) {
console.log(all.children.length)
all.children[0].remove();
}
}
Hopefully answer your question
const red = document.getElementById('red');
jQuery('#remove').on('click', () => {
const elements = $('#red').children('.home');
if(elements.length > 1) {
for( let i=0; i< elements.length - 1; ++i){
$(elements[i]).remove();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="red">
<div class="home">WHITE</div>
<div class="home">GREEN</div>
<div class="home">BLUE</div>
</div>
<button id="remove">Remove home</button>

Issues rendering handlebars to HTML

When I render my handlebars template in html, it looks like it's essentially skipping filling in the "handle bars" portion. I'm essentially printing messages with a title and content, and I'm using a "!each" helper to display all of my messages. I originally thought it was because it was because it was escaping the html around it, so I tried using a triple handle bar {{{ on each part however using the each helper with the triple stash gave me an error. Am I possibly using the handlebars incorrectly?
the typescript I used to render the HTML and my handlebars template is below:
public static refreshData(data: any) {
$("#indexMain").html(Handlebars.templates['main.hbs'](data));
//helper function for upvote button
Handlebars.registerHelper('getUButton', function (id) {
id = Handlebars.escapeExpression(id);
return new Handlebars.SafeString(
"<button type='button' class='btn btn-default up-button' id='u" + id + "'>Upvote</button>"
);
});
//helper function for downvote button
Handlebars.registerHelper("getDButton", function (id) {
id = Handlebars.escapeExpression(id);
return new Handlebars.SafeString(
"<button type='button' class='btn btn-default down-button' id='d" + id + "'>DownVote</button>"
);
});
// Grab the template script
var theTemplateScript = $("#main-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
//get messages from server and add them to the context
// This is the default context, which is passed to the template
var context = {
messages: data
}
console.log("context:")
console.log(context);
// Pass data to the template
var theCompiledHtml = theTemplate(context);
console.log(theCompiledHtml);
// Add the compiled html to the page
$("#messages-placeholder").html(theTemplate(context));
//add all click handlers
//get all buttons with id starting with u and set the click listerer
$(".up-button").click((event) => {
var id = $(event.target).attr("id").substring(1);
main.upvote(id)
});
//get all buttons with id starting with d and set the click listerer
$(".down-button").click((event) => {
var id = $(event.target).attr("id").substring(1);
main.downvote(id)
});
}
<script id="main-template" type="text/x-handlebars-template">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Current Messages</h3>
</div>
<div class="panel-body">
<div class="list-group" id="message-list">
<!-- for each message, create a post for it with title, content, upvote count, and upvote button -->
{{#each messages}}
<li class="list-group-item">
<span class="badge">Vote Count: {{likeCount}}</span>
<h4 class="list-group-item-heading">{{title}}</h4>
<p class="list-group-item-text">{{content}}</p>
<div class="btn-group btn-group-xs" role="group" aria-label="upvote">
{{getUButton id}}
</div>
<div class="btn-group btn-group-xs" role="group" aria-label="downvote">
{{getDButton id}}
</div>
</li>
{{/each}}
</div>
</div>
</div>
</script>
<div id="messages-placeholder"></div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Post New Message</h3>
</div>
<div class="input-group">
<span class="input-group-addon">Title</span>
<input id="newTitle" type="text" class="form-control" placeholder="Title" aria-describedby="newTitle">
</div>
<div class="input-group">
<span class="input-group-addon">Message</span>
<input id="newMessage" type="text" class="form-control" placeholder="Message" aria-describedby="newMessage">
</div>
<div class="btn-group" role="group" aria-label="create">
<button type="button" class="btn btn-default" id="postNewMessage">Post Message</button>
</div>
<span class="label label-danger" id="incompleteAcc"></span>
</div>
Okay, then it is likely the data provided to your template is not in the correct form. Here's a working snippet (with non-essentials stripped out). The data passed to your refreshData template must be an array. Make sure it isn't an object containing an array.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
</head>
<body>
<script>
let refreshData = (data) => {
// Grab the template script
var theTemplateScript = $("#main-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
//get messages from server and add them to the context
// This is the default context, which is passed to the template
var context = {
messages: data
};
console.log("context:", context);
// Add the compiled html to the page
$("#messages-placeholder").html(theTemplate(context));
}
$(() => {
var data = [
{ likeCount: 3, title: 'My Title', content: 'Some content'},
{ likeCount: 0, title: 'My 2nd Title', content: 'Some other content'}
];
refreshData(data);
})
</script>
<script id="main-template" type="text/x-handlebars-template">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Current Messages</h3>
</div>
<div class="panel-body">
<div class="list-group" id="message-list">
<!-- for each message, create a post for it with title, content, upvote count, and upvote button -->
{{#each messages}}
<li class="list-group-item">
<span class="badge">Vote Count: {{likeCount}}</span>
<h4 class="list-group-item-heading">{{title}}</h4>
<p class="list-group-item-text">{{content}}</p>
</li>
{{/each}}
</div>
</div>
</div>
</script>
<div id="messages-placeholder"></div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Post New Message</h3>
</div>
<div class="input-group">
<span class="input-group-addon">Title</span>
<input id="newTitle" type="text" class="form-control" placeholder="Title" aria-describedby="newTitle">
</div>
<div class="input-group">
<span class="input-group-addon">Message</span>
<input id="newMessage" type="text" class="form-control" placeholder="Message" aria-describedby="newMessage">
</div>
<div class="btn-group" role="group" aria-label="create">
<button type="button" class="btn btn-default" id="postNewMessage">Post Message</button>
</div>
<span class="label label-danger" id="incompleteAcc"></span>
</div>
</body>
</html>
When I am faced with issues like this, I eliminate different things until I either get clarity or something I removed fixes the problem. Now I have isolated where the problem lies. In your situation, the issue is likely the data being passed so verify that. Then try stripping out your helpers to see if they are causing issues.

How to add a link in javascript

I have the following Javascript that I am using to make a sort of flowchart where the user clicks through a set of questions. For certain responses i want to link to an external site where more info can be found. How do I add these links?
HTML
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row">
<div class="col-xs-12 text-right">
<button class="btn btn-default btn-corner" type="submit" data-bind="click: startOver, visible: queryData().id > 0">Start over</button>
</div>
</div>
</div>
<div class="container main">
<div class="row">
<div class="c12 text-center">
<h1 data-bind="text: queryData().text"></h1>
<h3 data-bind="text: queryData().subhead"></h3>
<div class="option-group" data-bind="foreach: queryData().answers">
<button class="btn btn-default btn-lg" type="submit" data-bind="click: $parent.goToTarget, text: text"></button>
</div>
<button class="btn btn-default" type="submit" data-bind="click: stepBack, visible: navHistory().length > 1">Previous Step</button>
</div>
</div>
</div>
<div class="push"></div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
<script src="app.js?v=0.4.0"></script>
<script>
</script>
</body>
</html>
The Javascript is as follows:
JS
var queries = [{
id: 0,
text: "Where to start?",
answers: [{
text: "Let's Begin!",
target: 1
}]
}, {
id: 1,
text: "Which genre do you want to start in?",
answers: [{
text: "Fantasy",
target: 100
}, {
text: "SciFi",
target: 2
}, {
text: "Neither",
target: 59
}]
}, {
id: 2,
text: "It's huge but it's worth it. The Cryptonomicon by Neal Stephenson",
answers: [{
text: "Amazon.co.uk",
target: "_blank"
}, {
text: "Amazon.com"
}]
}];
function QueryViewModel() {
var self = this;
self.querySet = ko.observable();
self.currentStep = ko.observable();
self.queryData = ko.observable();
self.sfw = ko.observable();
self.navHistory = ko.observableArray();
// Operations
self.goToTarget = function(obj) {
self.navHistory.push(self.currentStep());
self.currentStep(obj.target);
self.queryData(self.querySet()[obj.target]);
}
self.startOver = function() {
self.navHistory.removeAll();
self.goToTarget({target: 0});
}
self.stepBack = function() {
var lastStep = self.navHistory().length > 1 ? self.navHistory.pop() : 0;
self.currentStep(lastStep);
self.queryData(self.querySet()[lastStep]);
}
var paramsString = document.location.hash.substring(1);
var params = new Array();
if (paramsString) {
var paramValues = paramsString.split("&");
for (var i = 0; i < paramValues.length; i++) {
var paramValue = paramValues[i].split("=");
params[paramValue[0]] = paramValue[1];
}
}
params ? paramTarget = params['target'] : params = [];
self.sfw() ? self.querySet(queriesSFW) : self.querySet(queries);
if (paramTarget) {
self.navHistory.push(0);
self.currentStep(0);
self.goToTarget({target: paramTarget})
} else {
self.goToTarget({target: 0});
}
}
ko.applyBindings(new QueryViewModel());
In html you can do something like this:
<button type="button" onclick="window.open('https://google.com/', '_self')">Button</button>
You don't have to use a button, different elements can use onclick like text or images. This can also call js functions, just put the function name where "window.open..." is.
Of course the standard way to do it is
<a href='https://www.google.com/'>Link</a>
You can practice using js here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_inner_html
and learn more about it here: http://www.w3schools.com/js/js_intro.asp
I am not sure why you would show us the JSON for open a link to another page. Unless I misunderstood. This kind of basic information can be found by a quick Google search.
Add your link in the object like:
text: "Fantasy",
link: "http://www.stackoverflow.com",
target: 2
Now when you need to go to that link, use this function:
var link = obj.link;
window.open(link, "_blank");

Page keeps loading when inserting reference to jquery

I really feel this is a stupid question but I could not figure out:
Here my cshtml file, and it's rendered just fine:
#model CrashTestScheduler.Entity.Model.Channel
#{
string editFormat = string.Format("<button type='button' class='editForm' data-val-id=\"{0}\"><span class='ico-edit'></span></button>", ".Id");
const string DeleteFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('deleteChannel', { params:{ id: .Id } })\"><span class='ico-del'></span></button>";
const string EditFormat = "<button type='button' class='awe-btn' onclick=\"awe.open('editChannel', { params:{ id: .Id } })\"><span class='ico-edit'></span></button>";
}
<script>
$(function() {
awe.popup = bootstrapPopup;
});
var getChannelGroupNameHandler = function (item) {
if (item.ChannelGroupName == null || item.ChannelGroupName=='') {
item.ChannelGroupName = $("#ChannelGroupId option:selected").text();
}
}
</script>
<div id="wrap">
<div id="page-heading">
<ol class="breadcrumb">
<li>Home</li>
<li class="active">Channels</li>
<li style="display:none;"></li>
</ol>
</div>
<div class="container">
<div class="col-md-12" id="gridRowChannels">
<div class="col-md-12">
<div class="panel panel-midnightblue-header">
<div class="panel-heading">
<h3>Channel List</h3>
<div class="options">
</div>
</div>
<div class="panel-body">
<div class="row-sub">
<button type="button" id="btnAddProject" class="btn btn-primary" onclick="awe.open('createChannel')">
Add Channel
</button>
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("createChannel").Url(Url.Action("Create", "ChannelsGrid")).Success("itemCreated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Add").Title("Add Channel")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("deleteChannel").Url(Url.Action("Delete", "ChannelsGrid")).Success("itemDeleted('ChannelsGrid')").Parameter("gridId", "ChannelsGrid").Height(200).Modal(true).Title("Delete Channel").OkText("Delete")
</div>
<div class="row-sub">
#Html.Awe().InitPopupForm().Name("editChannel").Group("Channel").Url(Url.Action("Edit", "ChannelsGrid")).Success("itemUpdated('ChannelsGrid',getChannelGroupNameHandler)").OkText("Save").Title("Edit Channel")
</div>
<div class="row-sub">
#(Html.Awe().Grid("ChannelsGrid")
.Url(Url.Action("GetItems", "ChannelsGrid"))
.Columns(
new Column {Name = "Name", Header = "Channel Name", Sort = Sort.Asc},
new Column {Name = "ChannelGroup.Name", Header = "Channel Group", ClientFormat = ".ChannelGroupName"},
new Column {ClientFormat = DeleteFormat, Width = 50},
new Column {ClientFormat = EditFormat, Width = 50}
)
.Sortable(true)
.SingleColumnSort(true)
.LoadOnParentChange(false)
.PageSize(20)
.Groupable(false))
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12" id="pnlEditproject" style="display: none;">
</div>
</div>
</div>
But I want to use jquery to use jquery validation later on. So here I inserted them to the file.
<script src="~/Scripts/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
Now the file could not be rendered and the page keeps loading and loading. Any clues?
Looks like you already have access to jQuery library in this page since you are using...
$(function() {
awe.popup = bootstrapPopup;
});
Please remove the new references and try to view page source to find out the list of libraries that are already available.

angularjs tutorial code debug

im learning angularjs thru an Apress book and I've come across some code that doesnt work, ive tried to debug but my console isnt giving me any errors or anything. Maybe some experts can guide me thru whats wrong, thanks.
customFilters.js file
// Creating a custom filter
// arguments for the filter method is unique and a factory function that returns a filter function that does the actaul work
angular.module('customFilters',[]).filter('unique', function() {
return function(data, propertyname) {
if (angular.isArray(data) && angular.isString(propertyname)) {
var results = [];
var keys = {};
for (var i = 0; i < data.length; i++) {
var val = data[i][propertyname];
if (angular.isUndefined(keys[val])) {
keys[val] = true;
results.push(val);
}
}
return results;
} else {
return data;
}
}
});
sportsStore.js file
//declaring a dependency called customFilters that contains a unqiue filter
angular.module('sportsStore',['customFilters']);
// calling the angular.module method passing in sportsStore located in app.html
angular.module('sportsStore').controller('sportsStoreCtrl', function($scope) {
$scope.data = {
products: [
{name: "Product 1", description:"A product", category:"Category #1", price: 100},
{name: "Product 2", description:"A product", category:"Category #1", price: 110},
{name: "Product 3", description:"A product", category:"Category #2", price: 210},
{name: "Product 4", description:"A product", category:"Category #3", price: 202}
]
};
});
my productListControllers.js file
angular.module('sportsStore').controller('productListCtrl', function($scope,$filter){
var selectedCategory = null;
$scope.selectedCategory = function(newCategory) {
selectedCategory = newCategory;
};
$scope.categoryFilterFn = function(product) {
return selectedCategory == null || product.category == selectedCategory;
};
});
app.html file
<!DOCTYPE html>
<!-- We are defining the sportStore module here in the html tag-->
<html ng-app="sportsStore">
<head>
<title>Sports Store</title>
<link href="bootstrap.min.css" rel="stylesheet" />
<link href="bootstrap-theme.min.css" rel="stylesheet" />
</head>
<!-- Applying ng-controller to the body tagg -->
<body ng-controller="sportsStoreCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">Sports Store</a>
</div>
<div class="panel panel-default row" ng-controller="productListCtrl">
<div class="col-xs-3">
<a class="btn btn-block btn-default btn-lg" ng-click="selectCategory()">Home</a>
<!-- generating the navigation elements here -->
<a class="btn btn-block btn-default btn-lg" ng-repeat="item in data.products |orderBy:'category'| unique:'category'" ng-click="selectCategory(item)">{{item}}</a>
</div>
<div class="col-xs-8">
<!-- ng-repeat generates elements for each object in an array -->
<!-- we also create a local variable called item -->
<div class="well" ng-repeat="item in data.products | filter:categoryFilterFn">
<h3>
<strong>{{item.name}}</strong>
<span class="pull-right label label-primary">{{item.price | currency}}</span>
</h3>
<span class="lead">{{item.description}}</span>
</div>
</div>
</div>
<script src="angular.js"></script>
<script src="controllers/sportsStore.js"></script>
<script src="filters/customFilters.js"></script>
<script src="controllers/productListControllers.js"></script>
</body>
</html>
You have a typo in your html file. The function is selectedCategory not selectCategory.
There is a typo, the template says selectCategory and the controller says selectedCategory

Categories