How to print Json result to view in angular js - javascript

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]

Related

link button to another page

I know there a lot of things related to this stuff but I find it quite hard to implement
My current result is this. I added some details to the code to add to the DB then as I pressed the next button, it goes to another same page but its all about update and its not going anywhere to the page that I linked it to.
So far, this is what I've made to link the button to another page
if(!employeeExist){
$("#nextBtn").html("Next");
$("#nextBtn").removeClass("btn-success")
$("#nextBtn").addClass("btn-primary")
$('#a').hide();
$('#c').hide();
$('#d').hide();
$("#updateBtn").hide();
}else{
$("#updateBtn").html("Update");
$("#updateBtn").removeClass("btn-primary")
$("#updateBtn").addClass("btn-success")
$('#a').show();
$('#c').show();
$('#d').show();
$("#nextBtn").hide();
}
$("#updateBtn").click(updateCompanyInfo);
$("#nextBtn").click(updateCompanyInfo);
and this
if(employeeExist) {
$alertDiv("success","Company related information was successfully updated.",true);
} else {
$alertDiv("success","Company related information was successfully added.",true);
var fam = "${pageContext.request.contextPath}/employee/details/family?id="+empID;
window.location.replace(fam);
}
Here is the redirect part of my code
function Redirect() {
window.location="${pageContext.request.contextPath}/employee/details/family?id="+empID;
}
and the HTML part
<!-- Update -->
<div class="col-md-2 col-md-offset-8">
<br>
<div class="input-group">
<span class="input-group-btn">
<button id = "updateBtn" class="btn btn-success marginBtn">Update</button>
</span>
</div>
<br>
</div>
<!-- Next -->
<div class="col-md-2 col-md-offset-7">
<br>
<div class="input-group">
<span class="input-group-btn">
<button id = "nextBtn" class="btn btn-primary marginBtn" onclick="Redirect();">Next</button>
</span>
</div>
<br>
</div>
So how can I achieve this? Am I lacking something in the code or am I doing it the wrong way? Help me please!

Item rating in Algolia Search

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.

Browserify Page Specific Modules

I am new to Browserify but I think I am missing something. From what I can tell I have to load every single module for my app into bundle.js but I am totally lost as to how to call functions, objects etc for specific pages.
For instance, this is my main.js file:
var bootstrap = require('bootstrap');
var mainUI = require('./main-ui');
var foodGrid = require('./food-grid');
mainUI();
The mainUI(); bit is fine, as I need that to execute on every page to make my sidebar to work.
However, foodGrid is something that I only want to load when I visit the food page. If I do:
var bootstrap = require('bootstrap');
var mainUI = require('./main-ui');
var foodGrid = require('./food-grid');
mainUI();
foodGrid();
Then foodGrid() is called on every page, this is not correct.
foodGrid() is defined as:
module.exports = function () {
console.log('Test');
})
I can not see a way of getting this to work since everything is bundled into bundle.js, without doing some logic around the functions to determine if the user is on a certain page, which seems ridiculous.
My food page is:
#extends('layouts.master')
#section('title')
Enquiries
#stop
#section('body')
<div class="row">
<div class="col-xs-12">
<h3>Food</h3>
</div>
</div>
<div id="food_controls" class="row">
<div class="col-xs-9">
Control
</div>
<div class="col-xs-3">
<div class="input-group">
<span class="input-group-addon"><img width="20" src="{!!asset('images/loader.gif')!!}"><i class="fa fa-search"></i></span>
<input class="form-control" type="text" placeholder="Start typing to search...">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div id="foodGrid"></div>
</div>
</div>
#stop
#section('js')
{!! HTML::script('js/libs/kendo.all.min.js') !!}
<script>
enquiriesGrid();
</script>
#stop
The above gives me the error that foodGrid() is undefined.
Can someone tell me how to work with this? I must being missing something big.
(I am using Laravel 5, that is what all that blade syntax is)
elixir(function(mix) {
mix.browserify('main.js');
});

List.JS - Cannot read property 'childNodes' of undefined

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?

Angular.js Error: Duplicates in a repeater are not allowed - Track by index doesn't work as intended

I am going through a tutorial on the Ionic Framework, which is using Angular JS to create a simple Todo app. It creates a new task by using .push() to append a new task object onto an array of task objects (code is below).
I am getting this error when I try add more than one task.
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: task in tasks, Duplicate key: object:00C
http://errors.angularjs.org/1.2.4/ngRepeat/dupes?p0=task%20in%20tasks&p1=object%3A00C
I've tried using the solution as posted in this answer and this blog post, which suggest adding track by $index, but it doesn't work properly for me...
It does get rid of the error, but then when I add a new task it updates all of the objects in the array with that new task! And in my list of tasks within the ng-repeat block I can see each task is now the same as the one I just added.
What am I doing wrong here? Is it something to do with the objects that I'm pushing onto the array? I am new to Angular.js so perhaps I am missing something simple yet crucial?
Here is my HTML:
<body ng-app="todo" ng-controller="TodoCtrl">
<side-menus>
<!-- Center content -->
<pane side-menu-content>
<header class="bar bar-header bar-dark">
<h1 class="title">Todo</h1>
<!-- New Task button-->
<button class="button button-icon" ng-click="editTasks()">
<i class="icon ion-edit"></i>
</button>
<button class="button button-icon" ng-click="newTask()">
<i class="icon ion-compose"></i>
</button>
</header>
<content has-header="true">
<!-- our list and list items -->
<list>
<item ng-repeat="task in tasks track by $index">
{{task.title}}
</item>
</list>
</content>
</pane>
<!-- Left menu -->
<side-menu side="left">
<header class="bar bar-header bar-dark">
<h1 class="title">Projects</h1>
</header>
</side-menu>
<!-- Add a new task -->
<script id="new-task.html" type="text/ng-template">
<div class="modal">
<!-- Modal header bar -->
<header class="bar bar-header bar-secondary">
<h1 class="title">New Task</h1>
<button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button>
</header>
<!-- Modal content area -->
<content has-header="true">
<form ng-submit="createTask(task)">
<div class="list">
<label class="item item-input">
<input type="text" placeholder="What do you need to do?" ng-model="task.title">
</label>
</div>
<div class="padding">
<button type="submit" class="button button-block button-positive">Create Task</button>
</div>
</form>
</content>
</div>
</script>
</side-menus>
</body>
And here is my JS:
angular.module('todo', ['ionic'])
.controller('TodoCtrl', function($scope, Modal) {
// No need for testing data anymore
$scope.tasks = [];
// Create and load the Modal
Modal.fromTemplateUrl('new-task.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope,
animation: 'slide-in-up'
});
// Called when the form is submitted
$scope.createTask = function(task) {
console.log('task', task);
$scope.tasks.push(task);
console.log('$scope.tasks', $scope.tasks);
$scope.taskModal.hide();
};
// Open our new task modal
$scope.newTask = function() {
$scope.taskModal.show();
};
// Close the new task modal
$scope.closeNewTask = function() {
$scope.taskModal.hide();
};
});
The problem looks like you are not creating independent task instances. It appears that your modal is binding to a single task instance and attempting to add the same exact reference each time. Try something like the following.
In your JS:
// Open our new task modal
$scope.newTask = function() {
$scope.editTask = {};
$scope.taskModal.show();
};
In your HTML:
<form ng-submit="createTask(editTask)">
<div class="list">
<label class="item item-input">
<input type="text" placeholder="What do you need to do?" ng-model="editTask.title">
</label>
</div>
<div class="padding">
<button type="submit" class="button button-block button-positive">Create Task</button>
</div>
</form>
That creates a new editTask instance every time the newTask function is called and adds that new instance to the array. You should not need the track by $index code after those changes.

Categories