It's my first time when I use mustache.js and need some help, please.
Doing a html template builder and I am trying to grab data from JSON and HTML files, than show them into my page.
So I am using this script to get Default theme from JSON than to get the HTML:
$.getJSON('templates.json', function(json){
$.each(json, function(theme, val){
if(theme == 'Default'){
template.load('templates/'+val.url+'/template.html', function(response, status, xhr){
$(this).html(Mustache.render($(this).html(), {
tabs:val.tabs
}));
});
}
});
});
JSON:
{
"Default" : {
"url":"default",
"logo": "YOUR LOGO HERE",
"phone": "+1234567890",
"tabs": [
"About Us",
"Delivery",
"Payment",
"Shipping",
"Contact Us"
]
}
}
HTML:
{{#tabs.length}}
<div id="tabs">
{{#tabs}}
<input class="state" type="radio" title="tab1" name="tabs-state" id="tab1" checked />
{{/tabs}}
<div class="tabs flex-tabs">
{{#tabs}}
<label for="tab1" id="tab1-label" class="tab">{{.}}</label>
{{/tabs}}
{{#tabs}}
<div id="tab1-panel" class="panel active">[[{{.}}]]</div>
{{#tabs}}
</div>
</div>
{{/tabs.length}}
I just can't display the tabs. First time I tried with javascript to convert json into html, but Mustache was showing text instead of html. Now I am trying with conditions in html with no luck.
I also need to add numbers to each item, eg: "tab1", "tab2".. - is this {{#index}} good for that?
How can I add checked only for first items?
Also not sure if {{.}} this is displaying the name of my tab..
You've almost got this nailed, although have slightly misunderstood how to write the mustacheJS view. It's even simpler than you thought! See below. I've simplified the example, so you understand the concept.
Some explanation for below:
{{#Default}}{/Default}} represents looping over an object literal
{{#tabs}}{{/tabs}} presents looping over the object that exists within {{#Defaults}}.
{{.}} displays the entire contents of the object. If this was a complex object, it would be rendered as [object][object]. If you ever encounter this, you must name the object explicitly in your view.
<div class="tabs">
{{#Default}}
{{#tabs}}
<input class="state" type="radio" title="Tab1" name="tabs-state" checked/>
<div class=tabs flex-tabs>
{{.}}
</div>
{{/tabs}}
{{/Default}}
</div>
View Produced
<div class="tabs">
<div class=tabs flex-tabs>
About Us
</div>
<div class=tabs flex-tabs>
Delivery
</div>
<div class=tabs flex-tabs>
Payment
</div>
<div class=tabs flex-tabs>
Shipping
</div>
<div class=tabs flex-tabs>
Contact Us
</div>
</div>
Related
I am using Algolia in my web system and I really like this service. The only thing on which I am stuck is I want to show star rating of items, you can see picture attached below for more clarification.
I don't want rating widget. I have an attribute called rating that has float values like 3.54 etc. I am using Laravel 5.4
Image : https://img42.com/Xad0J
Algolia's Hits Widget
search.addWidget(
data = instantsearch.widgets.hits({
container: '#hits-container',
hitsPerPage: 10,
templates: {
item: function(data) {
return '<div class="row well_our well-sm_our"> <div class="col-md-3"> <img class="img-responsive" src="'+data.pic_path+'"> </div> <div class="col-md-6"> <div class="rest-list-heading">'+data.name+'</div> <div class="rest-list-para text-justify">'+data.description+'</div> </div> <div class="col-md-3 rest-coulmn-3"> <div title="Rating : rating" id="rating'+data.id+'"></div> <input type="hidden" id="ratingOfRest'+data.id+'" value="rating"> <div class="rest-list-para1" align="center">'+data.reviews+' <input type="hidden" id="restID'+data.id+'" value="id"></div> <div class="dotted-btn-rest" align="center"> View Menu </div> </div> </div>';
},
}
})
);
Laravel Blade:
<div id="hits-container"></div>
In order to do that you need to implement two things. One is a transformData, that will let you process your floats into elements that can be used in the the template.
You can find an example for the transformData of a star rating here. The other is the template. You can find the star rating template a little above the transform data.
The Problem
(Since posting this, I've gotten a little closer to solving it, but I'm still stuck. Please check the update at the end of the question).
I have a site that's been template using Mustache.js. When the site is run locally, it works fine. The templates are loaded, Mustache replaces the mustache tags with the given data, and the page renders as expected.
When the site is run from my (school) server however, it develops an odd issue. For whatever reason, Mustache.render is replacing all the mustache tags in my template with nothing (as in empty strings). Obviously, this is causing my site to load very wrong.
What I've Tried To Diagnose It
Using console logging, I tracked the loaded templates, and what Mustache produces. The results are below:
The data to plug into the templates (siteData.json):
{
"headerClasses": "mainHeader",
"headerTitle": "Uromastyces Fact Site",
"sideBarClasses": "mainSideBar",
"sideBarImgClasses": "sideBarImage",
"sideBarImgAlt": "A Picture of Pascal",
"sideBarImgSrc": "../images/pascal-cropped-shrunk.jpg",
"navBarClassNames": "navBar",
"navLinks": [
{
"name": "Home",
"link": "index.html"
}, {
"name": "Enclosure",
"link": "enclosure.html"
}, {
"name": "Diet",
"link": "diet.html"
}, {
"name": "Behavior and Life",
"link": "behaviorAndLife.html"
}, {
"name": "About Me",
"link": "aboutMe.html"
}
],
"uniqueBodyClasses": "uniqueBody",
"uniqueBodyContent": "DEFAULT UNIQUE BODY",
"footerClasses": "mainFooter",
"authorWrapperClasses": "footerAuthor footerWrapper",
"dateModifiedWrapperClasses": "footerModified footerWrapper",
"authorName": "Brendon Williams",
"lastModifiedDate": "DEFAULT LAST MODIFIED DATE",
"indexNavBarClasses": "indexNavBar"
}
Body Template (BodyTemplate.mustache):
<header class="{{headerClasses}}">
<h1>
{{headerTitle}}
</h1>
</header>
<aside class="{{sideBarClasses}}">
<img class="{{sideBarImgClasses}}" src="{{sideBarImgSrc}}" alt="{{sideBarImgAlt}}">
<nav class="{{navBarClassNames}}">
<ul>
{{#navLinks}}
<li>{{name}}</li>
{{/navLinks}}
</ul>
</nav>
</aside>
<section class="{{uniqueBodyClasses}}">
<div id="indexDiv">
<div id="indexContents"></div>
</div>
{{> uniqueBodyContent}}
</section>
<footer class="{{footerClasses}}">
<span class="{{authorWrapperClasses}}">
Author: {{authorName}}
</span>
<span class="{{dateModifiedWrapperClasses}}">
Last Modified: {{> lastModifiedDate}}
</span>
</footer>
<script src="./js/Indexer.js"></script>
Here's where it differs. After running the above files through Mustache.render locally, here are the results:
<header class="mainHeader">
<h1>
Uromastyces Fact Site
</h1>
</header>
<aside class="mainSideBar">
<img class="sideBarImage" src="../images/pascal-cropped-shrunk.jpg" alt="A Picture of Pascal">
<nav class="navBar">
<ul>
<li>Home</li>
<li>Enclosure</li>
<li>Diet</li>
<li>Behavior and Life</li>
<li>About Me</li>
</ul>
</nav>
</aside>
<section class="uniqueBody">
<div id="indexDiv">
<div id="indexContents"></div>
</div>
<h4>Introduction</h4>
<h5>Hi...</h5>
<p>
I created this site to...
</p>
<p>
...
</p>
<p>
...
</p>
<h4>Contact Me</h4>
<p>
Want to send me a message? Use the form below:
</p>
<form enctype="text/plain" method="post" action="mailto:brendonw5#gmail.com">
<label class="contactLabel">Subject:</label>
<input class="contactInput" type="text" name="subject">
<label class="contactLabel">Body:</label>
<input class="contactInput" type="text" name="body">
<input type="submit" name="submit" value="Submit">
</form>
</section>
<footer class="mainFooter">
<span class="footerAuthor footerWrapper">
Author: Brendon Williams
</span>
<span class="footerModified footerWrapper">
Last Modified: 15.12.26
</span>
</footer>
<script src="./js/Indexer.js"></script>
Exactly as I'd expect. All the mustache tags were removed, and replaced with the corresponding data from the JSON
However, here's the results when run from my school's server (The exact same code):
<header class="">
<h1>
</h1>
</header>
<aside class="">
<img class="" src="" alt="">
<nav class="">
<ul>
</ul>
</nav>
</aside>
<section class="">
<div id="indexDiv">
<div id="indexContents"></div>
</div>
<h4>Introduction</h4>
<h5>Hi...</h5>
<p>
I created this site to...
</p>
<p>
...
</p>
<p>
...
</p>
<h4>Contact Me</h4>
<p>
Want to send me a message? Use the form below:
</p>
<form enctype="text/plain" method="post" action="mailto:brendonw5#gmail.com">
<label class="contactLabel">Subject:</label>
<input class="contactInput" type="text" name="subject">
<label class="contactLabel">Body:</label>
<input class="contactInput" type="text" name="body">
<input type="submit" name="submit" value="Submit">
</form>
</section>
<footer class="">
<span class="">
Author:
</span>
<span class="">
Last Modified: 15.12.26
</span>
</footer>
<script src="./js/Indexer.js"></script>
Notice how all of the mustache tags were simply removed instead of being replaced by the data.
I know everything is being downloaded fine, so it's not a path issue:
While I've been using mustache for about a week, I have no idea how to diagnose a problem like this. The above snippets were the result of console logging, so I've verified the input going into Mustache.render, and it all checks out. And again, this only happens when it's hosted remotely.
Here's my rendering module (templateLoader.js) (The chunk of console logs in the middle of renderPage is the source of the above snippets via the Developer Cosole):
var TemplateLoader = {
/**
* Draws the templated page, along with the given unique body.
*
* #param {string|Node} uniqueBodyElement Data representing the unique body to display. Should either be a string
* of HTML, or a DOM element containing the HTML.
* #param {string} lastModifiedDate The date that the page was last modified.
*/
renderPage: function(uniqueBodyElement, lastModifiedDate) {
var data;
var headTemplate;
var bodyTemplate;
var articleTemplate;
//Wait until all data is available
$.when(
$.get("./templates/siteData.json", function(d){ data = d }),
$.get("./templates/HeadTemplate.mustache", function(hT){ headTemplate = hT }),
$.get("./templates/BodyTemplate.mustache", function(bT){ bodyTemplate = bT }),
$.get("./templates/ArticleTemplate.mustache", function(aT){ articleTemplate = aT })
).done(function() {
Helpers.doWithMustache(function() {
var partial = TemplateLoader.getTemplatePartial(uniqueBodyElement);
partial.lastModifiedDate = lastModifiedDate;
var renderedHead = Mustache.render(headTemplate, data);
var renderedBody = Mustache.render(bodyTemplate, data, partial);
var renderedArticleBody = Mustache.render(articleTemplate, {}, { articleBody: renderedBody });
console.group();
console.log("Data: \n" + data);
console.log("Body Template: \n" + bodyTemplate);
console.log("Article Template: \n" + articleTemplate);
console.log("Rendered Body: \n" + renderedBody);
console.log("Rendered Article Body: \n" + renderedArticleBody);
console.groupEnd();
$('head').append(renderedHead);
$('body').html(renderedArticleBody);
console.log("Templates Loaded.");
});
}).fail(function() {
console.error("Failed to fetch templates or site data.")
});
},
getTemplatePartial: function(templateData) {
var uniqueBodyString;
if (typeof templateData === "string") {
uniqueBodyString = templateData
} else {
uniqueBodyString = templateData.innerHTML;
}
return {
uniqueBodyContent: uniqueBodyString
};
}
};
var Helpers = {
doWithMustache: function(f) {
$.getScript("./js/mustache.min.js", function() {
f();
}).fail(function() {
console.error("Failed to fetch mustache script.")
});
}
};
And here's the full results of the log:
Data:
{
"headerClasses": "mainHeader",
headerTitle: "Uromastyces Fact Site",
"sideBarClasses": "mainSideBar",
"sideBarImgClasses": "sideBarImage",
"sideBarImgAlt": "A Picture of Pascal",
"sideBarImgSrc": "../images/pascal-cropped-shrunk.jpg",
"navBarClassNames": "navBar",
"navLinks": [
{
"name": "Home",
"link": "index.html"
}, {
"name": "Enclosure",
"link": "enclosure.html"
}, {
"name": "Diet",
"link": "diet.html"
}, {
"name": "Behavior and Life",
"link": "behaviorAndLife.html"
}, {
"name": "About Me",
"link": "aboutMe.html"
}
],
"uniqueBodyClasses": "uniqueBody",
"uniqueBodyContent": "DEFAULT UNIQUE BODY",
"footerClasses": "mainFooter",
"authorWrapperClasses": "footerAuthor footerWrapper",
"dateModifiedWrapperClasses": "footerModified footerWrapper",
"authorName": "Brendon Williams",
"lastModifiedDate": "DEFAULT LAST MODIFIED DATE",
"indexNavBarClasses": "indexNavBar"
}
templateLoader.js (41,14)
Body Template:
<header class="{{headerClasses}}">
<h1>
{{headerTitle}}
</h1>
</header>
<aside class="{{sideBarClasses}}">
<img class="{{sideBarImgClasses}}" src="{{sideBarImgSrc}}" alt="{{sideBarImgAlt}}">
<nav class="{{navBarClassNames}}">
<ul>
{{#navLinks}}
<li>{{name}}</li>
{{/navLinks}}
</ul>
</nav>
</aside>
<section class="{{uniqueBodyClasses}}">
<div id="indexDiv">
<div id="indexContents"></div>
</div>
{{> uniqueBodyContent}}
</section>
<footer class="{{footerClasses}}">
<span class="{{authorWrapperClasses}}">
Author: {{authorName}}
</span>
<span class="{{dateModifiedWrapperClasses}}">
Last Modified: {{> lastModifiedDate}}
</span>
</footer>
<script src="./js/Indexer.js"></script>
templateLoader.js (42,14)
Article Template:
<section>
{{> articleBody}}
</section>
templateLoader.js (43,14)
Article Template:
<section>
{{> articleBody}}
</section>
templateLoader.js (43,14)
Rendered Article Body:
<section>
<header class="">
<h1>
</h1>
</header>
<aside class="">
<img class="" src="" alt="">
<nav class="">
<ul>
</ul>
</nav>
</aside>
<section class="">
<div id="indexDiv">
<div id="indexContents"></div>
</div>
<h4>Introduction</h4>
<h5>Hi, I'm Brendon, and I'm a long-time reptile and Uromastyx owner.</h5>
<p>
I created this site to act as a centralized collection of facts on Uromastyces. The conditions that Uromastyces should be housed in are quite different than most other reptiles, so it can be confusing to new owners as to what the correct conditions are, and what they can be fed.
</p>
<p>
To the best of my ability, I will reference external sites and provide links to the original information. Note though that new information about Uromastyces may come to light after the publication of this site, so I can't guarantee that this information will forever remain in-date, and that contradictory information won't appear later; although I'll do my best to evaluate all of the sources I use.
</p>
<p>
In the top-left of every page is my current Uromastyx, <em>Pascal</em>. She was injured in-transit on the way to my Dad's wholesale warehouse (her right eye was damaged) and was deemed unsellable, so I adopted her to ensure that she can still live a long-life. Besides her lack-of a left eye, she's so healthy, you'd never know that she's injured (except when she
walks in circles looking for food).
</p>
<h4>Contact Me</h4>
<p>
Want to send me a message? Use the form below:
</p>
<form enctype="text/plain" method="post" action="mailto:brendonw5#gmail.com">
<label class="contactLabel">Subject:</label>
<input class="contactInput" type="text" name="subject">
<label class="contactLabel">Body:</label>
<input class="contactInput" type="text" name="body">
<input type="submit" name="submit" value="Submit">
</form>
</section>
<footer class="">
<span class="">
Author:
</span>
<span class="">
Last Modified: 15.12.26
</span>
</footer>
<script src="./js/Indexer.js"></script></section>
templateLoader.js (45,14)
Templates Loaded.
templateLoader.js (51,14)
Any guidance at all here would be appreciated.
Update:
So, while debugging it, I found out the potential source of the problem, but have no idea how to resolve it. When debugging it locally, the data object (inside renderPage) is interpreted by Edge as a JS object, and lists each of its attributes. When it's remote however, the data object is being interpreted as a String (local is on the left, remote on the right):
So, the issue seems to be that the data.json isn't being read properly on the server side.
I should note that locally, I'm using Windows, but the school server is "Apache/2.2.3 (Red Hat)" (according to Edge's Network tab). I changed the returns from \r\n to \n to adhere to Unix standards, but it didn't change anything.
I've run the JSON file through all of the top JSON validators, and it checks out in all of them, so it doesn't seem to be a formatting issue.
It looks like you're not parsing JSON data from the AJAX response. The document is read as plain text. (Take a look at your data variable.)
You can use JSON.parse(txt) or jQuery's AJAX shorthand $.getJSON(...).
I cannot seem to figure this out. I've already tried $(document).ready and still doesn't work for me. I've also tried making a for loop specifically for these two value names to save the results to a var and pass it in that way. I've also tried putting the input with the class and id with search inside of the parent div and outside. Essentially like it in the nav bar. Using list.js & knockout.js btw. Im getting my venues using an ajax request using foursquares api.
JS:
var options = {
valueNames: ['name', 'category']
};
var userList = new List('search', options);
HTML:
<body>
<nav>
<h1 class="formattedH1">Downtown SA,TX</h1>
<span>
<input type="search" placeholder="Search" class="search" id="search">
<input type="button" class="sort searchButton" value="List"></input>
</span>
</nav>
<div id="map" class="map"></div>
<div class="list">
<input type="search" placeholder="Search" class="search" id="search">
<h1>My Top 5</h1>
<!-- Square card -->
<div class="card" id="favViewModel" data-bind="foreach: favList">
<div class="expand">
<h2 class="venueName" data-bind="text:name"></h2>
</div>
<div class="cardSupport" data-bind="attr: {src: image()}">
</div>
<div class="cardSupport" data-bind="text:address">
</div>
<a data-bind="attr: {href: website()}">Website</a>
</div>
<h1>Foursquare Recommended</h1>
<div class="card" id="recViewModel" data-bind="foreach: recommendedSpotList ">
<div class="expand">
<h2 class="venueName" data-bind="text:name"></h2>
</div>
<div class="cardSupport" data-bind="text:location">
</div>
<div class="cardSupport" data-bind="text:category">
</div>
<div class="cardSupport" data-bind="text:rating">
</div>
</div>
<script src="js/tester123.js"></script>
I fixed the same problem with some comments on the github page of the project, just make sure to have the same names as the examples and it will work, everything must be in a <div> and the ul must have the class list
Like this
<div id="hacker-list">
<ul class="list"></ul>
</div>
Link: https://github.com/javve/list.js/issues/9
I found my answer browsing other similar projects, so simple now. Thought it might help someone in case they ran across this. It was that since I was making an ajax call I had to to place the call to ko.applybindings inside the ajax request. The binding was out of scope, if you think about it make's sense especially if your request fails. Why even attempt to still bind the values of the request. HTML as above, and for JS ajax request please see below:
JS:
$.ajax({
url: 'https://api.foursquare.com/v2/venues/explore',
dataType: 'json',
data: 'data',
async: true,
success: function(data) {
venues = data['response']['groups'][0]['items'];
//This is where I had to place the binding to get it to render properly.
ko.applyBindings(new recommendedViewModel(), document.getElementById('recViewModel'));
},
error: function() {
alert("An error occurred.");
}
});
"Hello World" example of this error.
Where?
https://listjs.com/api/#listClass
listClass String, default: "list" What is the class of the
list-container.
Case one (Missing list class):
/* error example */
var options = {
valueNames: [ 'name', 'born' ],
};
var userList = new List('users', options);
<!-- error example -->
<div id="users">
<input class="search" placeholder="Search" />
<button class="sort" data-sort="name">
Sort by name
</button>
<ul data-missing-list-class class="">
<li>
<h3 class="name">John</h3>
<p class="born">1986</p>
</li>
</ul>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
Case two (custom listClass missing):
I declare listClass to be no_such_class. The code trying to read childNodes of undefined.
/* error example */
var options = {
valueNames: [ 'name', 'born' ],
listClass: "no_such_class" /* the error */
};
var userList = new List('users', options);
<!-- error example -->
<div id="users">
<input class="search" placeholder="Search" />
<button class="sort" data-sort="name">
Sort by name
</button>
<ul class="list">
<li>
<h3 class="name">No such class</h3>
<p class="born">1986</p>
</li>
</ul>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
**the error will not throw under stackoverflow snippet
Extra
Remember to not confuse between:
id or element
Id the element in which the list area should be initialized. OR the
actual element itself.
new List(id/element, options, values);
VS:
listClass
What is the class of the list-container?
Hello I am new to angular js , I need some help that i have one edit form in angular js when user click on edit it redirect to edit form but i am getting some issues that my json result look like :
[{"0":"3",
"1":"The only people for me are the mad ones",
"2":"“The only people for me are the mad ones, the ones who are mad to live, mad to talk, mad to be saved, desirous of everything at the same time, the ones who never yawn or say a commonplace thing, but burn, burn, burn like fabulous yellow roman candles exploding like spiders across the stars.”",
"3":"2015-05-08 13:01:58",
"id":"3","title":"The only people for me are the mad ones",
"description":"“The only people for me are the mad ones, the ones who are mad to live, mad to talk, mad to be saved, desirous of everything at the same time, the ones who never yawn or say a commonplace thing, but burn, burn, burn like fabulous yellow roman candles exploding like spiders across the stars.”",
"created_on":"2015-05-08 13:01:58"
}]
I want to know how to print my title , description in view.
Here is my controller file: where i get the data from database:
var myApp = angular.module("blogapp",[]);
myApp.config(['$routeProvider',function($routeProvider){
$routeProvider
.when('/home',{
templateUrl:'home.html',
controller:'blogcontroller'
})
.when('/list',{
templateUrl:'list.html',
controller:'blogcontroller'
})
.when('/add',{
templateUrl:'add.html',
controller:'addcontroller'
})
.when('/edit/:Blogid',{
templateUrl:'edit.html',
controller:'editcontroller'
})
.otherwise({
redirectTo:'/home'
});
}]);
myApp.controller('blogcontroller',function ($scope,$http){
$http({method: 'GET' , url: 'getallblog.php'}).success(function(data){
$scope.allblog = data;
console.log(data);
});
// DELETE blog HERE
$scope.removeRow= function(id){
$http.post("removeblog.php",{'id' : id}).success(function(data,status,headers,config){
window.location='index.html';
console.log("Deleted Successfully");
});
};
// delete blog code ends here
});
myApp.controller('addcontroller',function ($scope,$http){
/// New Post Here
$scope.new_post =function(){
$http.post("addblog.php" ,{'title' : $scope.title ,'description' : $scope.description }).success(function(data,status,headers,config){
window.location='index.html';
console.log("inserted Successfully");
});
};
// New Post ends Here
});
myApp.controller('editcontroller',function ($scope,$http,$routeParams){
$scope.Blogid = $routeParams.Blogid;
$http.post("getblog.php",{'id' : $scope.Blogid}).success(function(data){
$scope.editit = data; /// here i get the resuly want to pass it t view
console.log(data);
});
});
My edit html form : edit.html
<!-- Page Content -->
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-6">
<h1 class="page-header">
Angular Blog
</h1>
<div >
<form class="form-signin">
<h2 class="form-signin-heading">Modify // want to print title here </h2>
<div class="row">
<div class="col-md-12">
<label for="posttitle" class="sr-only">Email address</label>
<input type="text" id="posttitle" class="form-control" ng-model="{{title}}" required="" value=""><br>
<span>Title : // want to print title here</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<label for="postdetails" class="sr-only">Password</label>
<textarea id="postdetails" class="form-control" ng-model="description" required=""></textarea>
<br>
<span>Blog Description: // want to print description here</span>
</div>
</div>
<br>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<button class="btn btn-lg btn-primary btn-block" type="button" ng-click="edit_post()" name="editblog">Modify Now</button>
</div>
<div class="col-md-3"></div>
</div>
</form>
</div>
</div>
<div class="col-md-2"></div>
<!-- Blog Sidebar Widgets Column -->
<div ng-include="'includes/sidebar.html'">
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
to print your title, you first need to replace this line in JS:
$scope.allblog = data;
with
$scope.allblog = data[0];
Now, you can write in HTML the following statement:
{{allblog.title}}
Something like this:
<span>Blog Description: {{allblog.description}}</span>
Or
<span>Blog Description: <span ng-bind-html ="allblog.description"></span></span>
if your allblog is an array use allblog[0]
I'm attempting to push a new object with some key:value pairs into an array using AngularJS, and seem to be running into some trouble.
Here's the html:
<div class="small-12 medium-6 large-6 columns">
<div id="addSubTarget">
<p>Add Targets</p>
<input type="text" ng-model="sublevel.tagName">
<button type="button" class="resultsButton" ng-click="addTag()">Submit</button>
</div>
<div id="addSubTargetBox">
<p>Targets Added</p>
<div id="targetAddedBox">
<div class="targetAddedInBox" ng-repeat="tag in tagsFeed track by $index">
{{tag}}
<i class="fa fa-trash-o" title="Delete this tag" ng-click="deleteTag($index)"></i>
</div>
</div>
</div>
</div>
<div class="small-12 medium-6 large-6 columns">
<div class="sublevelAddTextArea">
<p>Instructions</p>
<textarea rows="4" ng-model="sublevel.instructions"></textarea>
</div>
<div class="sublevelAddTextArea">
<p>Response</p>
<textarea rows="4" ng-model="sublevel.response"></textarea>
</div>
</div>
And the button here:
<button type="button" class="resultsButton" ng-click="submitNewSub()">Submit</button>
Here's the function in the controller:
$scope.submitNewSub = function(){
var arrayForUse = [];
arrayForUse.push({
tag: $scope.tagsFeed,
instructions: $scope.sublevel.instructions,
response:$scope.sublevel.response
});
console.log(arrayForUse);
$scope.listTable.push(arrayForUse);
}
I am using a hard coded array for testing it looks like this:
$scope.listTable = [{
tag: "tags 1",
instructions: "instructions 1",
response: "response 1"
},
{
tag: "tags 2",
instructions: "instructions 2",
response: "response 2"
}];
I basically need those inputs to push onto that array in that structure so angular two-way data binding will update my front end, however something seems to not be working for me.
I think you want to push each element from the arrayForUse array one by one, not the whole array at once. Therefore you will want to change $scope.listTable.push(arrayForUse) by:
Array.prototype.push.apply($scope.listTable, arrayForUse);
Which takes each element in arrayForUse and pass it to the push method as a single call (equivalent to: $scope.listTable.push(arrayForUse[0], arrayForUse[1], arrayForUse[2], ...);
The code you have above is pushing an array onto an array:
var arrayForUse = [];
arrayForUse.push({tag:$scope.tagsFeed, instructions:$scope.sublevel.instructions, response:$scope.sublevel.response});
$scope.listTable.push(arrayForUse);
Is this what you want? Your hardcoded test array above seems to indicate you just need an array.