$scope array not holding value for ng-repeat - javascript

I am trying to use an ng-repeat on data that is fetched from an api (returned as JSON) When I do a console.log($scope.wines) before the end of the function it holds the value but then at the end of the function $scope.wines is empty again. I feel that this is causing my ng-repeat="wine in wines" isn't showing up correctly.
Here is my JS:
app.controller("MainController", function($scope){
var api_key = "22x";
$scope.wines = [];
// Search Wine Function
$scope.SearchWine = function(){
$scope.wines = [];
var search_api_url = "http://services.wine.com/api/beta2/service.svc/json/catalog?search=" + $scope.wine + "&size=200&apikey=" + api_key;
var i = 1;
$("#wine_list").html("");
$(".loading").show();
$(".alert").hide();
$("input[type='text']").val("").focus();
$.getJSON(search_api_url, function(data) {
$.each(data, function(key, value) {
if(key == "Products") {
$.each(value.List, function(k, v) {
$scope.wines.push(v);
});
console.log($scope.wines);
$(".loading").hide();
}
});
console.log($scope.wines);
});
console.log($scope.wines);
}; //End SearchWine
});
and here is my HTML
<div ng-controller="MainController">
<header>
<a href="http://powersearch.bestwine.com" class="brand">
<img src="assets/images/logo.png" alt="">
</a>
<div class="col-md-6 col-md-offset-3">
<form class="search_form">
<div class="input-group">
<input type="text" class="form-control" ng-model="wine" placeholder="Search by Winery or AVA...">
<span class="input-group-btn">
<button class="btn btn-primary" type="submit" ng-click="SearchWine()">Search</button>
</span>
</div><!-- /input-group -->
<p class="help-block">You can also search international! Try typing in 'Burgundy'</p>
</form>
</div>
</header>
<div class="container">
<div class="col-md-12">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th class='text-center'>#</th>
<th>Wine Name</th>
<th>Wine Appellation</th>
<th>Wine Price</th>
<th>Favorite</th>
</tr>
</thead>
<tbody id="wine_list">
<tr ng-repeat="wine in wines">
<td>{{ wine.Name }}</td>
<td>{{ wine.Appellation.Name }}</td>
</tr>
</tbody>
</table>
<div class="alert alert-info">Type in above to start.</div>
</div>
</div>
</div>
And here is what console displays when running:
If you need anything else, let me know!

Use $resource or $http to fetch data instead of jQuery $.getJson
Here you have detailed answer: AngularJS: factory $http.get JSON file
Additionally avoid using jQuery like this in your Angular code:
$("#wine_list").html("");
$(".loading").show();
$(".alert").hide();
$("input[type='text']").val("").focus();
...
Tasks like this can be handled by angular directives ng-show, ng-hide etc.

Related

How can I get specific value from returned response

I'm trying to create shopping cart with laravel. I have a little problem to update cart items price onchange quantity number input. Ajax sends value and returns in array. But this time the problem is beginning.
This is my cart blade:
#extends('user.addons.app')
#push('customCss')
<link rel="stylesheet" href="
{{asset('/user/assets/css/numberinput.css')}}">
#endpush
#section('content')
#include('user.modules.header')
#include('user.modules.lsidebar')
<div id="cart-page-wrapper" class="pt-86 pt-md-56 pt-sm-46 pb-50 pb-md-20
pb-sm-10">
<div class="container">
<div class="row">
<div class="col-lg-8">
<div class="shopping-cart-list-area">
#include('user.modules.cart_data')
<div class="cart-coupon-update-area d-sm-flex justify-
content-between align-items-center">
<div class="coupon-form-wrap">
<form action="#" method="post">
<input type="text" placeholder="Coupon
Code"/>
<button class="btn-apply">Apply
Button</button>
</form>
</div>
<div class="cart-update-buttons mt-xs-14">
<button class="btn-clear-cart">Clear
Cart</button>
<button class="btn-update-cart">Update
Cart</button>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<!-- Cart Calculate Area -->
#include('user.modules.cartcalculate')
</div>
</div>
</div>
</div>
#include('user.modules.footer')
#endsection
#push('customJs')
#endpush
This is my cart_data blade:
<div class="shopping-cart-table table-responsive">
<table class="table table-bordered text-center" >
<thead>
<tr>
<th>Products</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
#foreach($carts as $cart)
<tr>
<td class="product-list">
<div class="cart-product-item d-flex align-items-center">
<div class="remove-icon">
<button><i class="fa fa-trash-o"></i></button>
</div>
<a href="single-product-sticky.html" class="product-
thumb">
<img src="{{asset($cart['image'])}}" alt="Product"/>
</a>
<a href="single-product-tab-left.html" class="product-
name">{{$cart['title']}}</a>
</div>
</td>
<td>
<span class="price">$ {{$cart['price']}}</span>
</td>
<td>
<input type="hidden" value="{{$cart['id']}}"
id="mon{{$cart['id']}}">
<div class="quantity">
<input type="number" min="1" max="9" step="1" value="
{{$cart['quantity']}}" id="qty{{$cart['id']}}">
</div>
</td>
<td>
<span class="price" id="toss{{$cart['id']}}">
{{$cart['price'] * $cart['quantity']}}
</span>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<script src="{{asset('/assets/plugins/jquery/jquery.min.js')}}">
</script>
<script src="{{asset('/user/assets/js/numberinput.js')}}"></script>
<script>
#foreach($carts as $cart)
$("#qty{{$cart['id']}}").change(function(e){
e.preventDefault();
var value = $("#qty{{$cart['id']}}").val();
var id = $("#mon{{$cart['id']}}").val();
var inputQuantityElement = $("#x{{$cart['id']}}");
$.ajax({
type: 'post',
url: '/cartupdate',
data: {_token: '{{ csrf_token() }}',value:value, id:id},
success : function(response) {
$(inputQuantityElement).val(response);
}
});
});
#endforeach
</script>
And this is my function in controller:
public function cartupdate(Request $request)
{
$cartss = Cart::find($request['id']);
$quantity = $cartss->quantity;
if($quantity < $request['value'])
{
$update = $cartss->quantity+1;
}
else if($quantity > $request['value'])
{
$update = $cartss->quantity-1;
}
else
{
die;
}
$cartss->update(['quantity' => $update]);
$carts = Cart::where('user_id', Auth::user()->id)->get();
foreach ($carts as $cart)
{
$id[] = $cart['id'];
$pric[] = $cart['price'] * $cart['quantity'];
}
return $pric;
}
I want to change dynamicly prices when user clicked quantity input
In your cartupdate() function, return $pric won't give you the result because $pric is declared inside foreach(). Change it to:
$pric = 0;
foreach ($carts as $cart) {
$pric += $cart['price'] * $cart['quantity'];
}
return $pric;
will give you the total. But, I guess you are trying to get a new price for a particular cart. If so, change your cartupdate() function to:
public function cardupdate(Request $request) {
$cart = Cart::find($request['id']);
$quantity = $cart->quantity;
if($quantity < $request['value'])
{
$quantity++;
}
else if($quantity > $request['value']){
$quantity--;
}
$cart->update(['quantity' => $quantity]);
return $quantity*$cart->price;
}
To update the price in the view, you can use
document.getElementById("toss{{$cart['id']}}").innerHTML = response;
Personally, I suggest you to try Vue.js to build your application. Laravel + Vue.js is a good combination. It much easier to build complex application like this.
Sorry for my bad english :)

Displaying JSON content in table rows using angularjs and codeigniter

I'm just trying to fetch contents from server and display it in a table using Angularjs. I'm been trying this from a while, but did not got any solution yet. Btw, I'm working on CodeIgniter framework.
Here is my CodeIgniter controller;
public function list_agents() {
if($this->is_logged_in ()) {
$agents = $this->generic_model->general_fetch('agent_master');
echo json_encode($agents);
}
else {
redirect(base_url());
}
}
In the above code, instead of echo I used print, print_r also.. But still its not working.
Here is my js file function;
(function () {
var addApp = angular.module('agentApp', ['ngRoute']);
addApp.controller('agentAddController', function ($scope, $http, growl) {
$scope.receivedData = [];
$http({
method : 'POST',
url : 'agent/list_agents',
headers : {
"Content-Type" : "application/json"
}
}).then(function (data) {
$scope.receivedData = JSON.parse(data);
});
});
})();
And in this above code I used with and without JSON.parse function. Didn't got the correct result.
Here is my view;
<section class="content" ng-app="agentApp" ng-controller="agentAddController">
<div class="row">
<div class="col-md-12">
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Manage Agents</h3>
</div>
<div class="box-body">
<table class="table table-striped table-bordered" id="agents_table">
<thead>
<tr>
<th>Sl No.</th>
<th>Agent Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<div ng-repeat="data in receivedData">
<tr>
<td>{{ $index + 1 }}</td>
<td>{{ data.agent_name }}</td>
<td><button class="btn btn-warning btn-xs"><i class="fa fa-trash" aria-hidden="true"></i></button></td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
<th>Sl No.</th>
<th>Agent Name</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</section>
I know if I put ng-repeat inside tr tag I'll get the perfect result, but I don't want to do that because, I'm working with adminLTE. So there is a function DataTable() in adminLTE where it'll apply search and pagination to the table. If I give ng-repeat to tr, these functionalities can not be added.
Try: $scope.receivedData = JSON.parse(data.data);
The response object is not only the data itself, that's why the 5 rows. It gives back, data, headers, status, etc...
https://docs.angularjs.org/api/ng/service/$http

Angular.js - Redirection is cleaning my $scope(?)

I have an $ngController that is being used in two views. The first view has an <table> with ng-repeat that lists all my data from the db.
I get the selected object form the table by using get($index) and set it to a $scope variable.
The problem is that when i cannot use this same $scope variable on the other view, because its value is undefined. Both views share the same ng-controller.
My Question is: is the redirection cleaning my $scope? Is there any way i can share this data between pages since my application isn't single page?
Things i tried:
1 - Share data through a factory
2 - Using $rootScope
First View - Table with ng-repeat
<table class="table table-striped">
<thead>
<tr>
<th>CNPJ</th>
<th>Razão Social</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="company in companies | filter:{companyName:searchString}">
<td> {{ company.cnpj }}</td>
<td> {{ company.companyName }}</td>
<td>
Visualizar
<button type="button" class="btn btn-warning btn-xs">Editar</button>
<button type="button" class="btn btn-danger btn-xs">Deletar</button>
</td>
</tr>
</tbody>
</table>
Controller
angular.module("distCad").controller("adminCtlr", function($scope, $http, config, $window, $cacheFactory){
$scope.searchTerm = null;
$scope.hideSearcAlert = true;
$scope.companies = [];
$scope.cache = $cacheFactory('companyCache');
$scope.expireLogin = function(){
localStorage.removeItem("type");
$window.location.href = "/";
}
$scope.getResults = function(){
$scope.searchTerm = true;
$http.get("/api/companies").then(
function successCallback(response){
$scope.companies = response.data;
},
function errorCallback(response){
console.log("aaaa" + response);
}
);
}
$scope.getCompany = function(){
return $scope.cache.get("company");
}
$scope.setCompanyFromTable = function(index){
$scope.cache.put("company", $scope.companies[index]);
}
});
Destination View - Part where i am testing
<div class="container" ng-init="getCompany()">
<div class="row">
<div class="col-md-12">
<h2>Dados da empresa {{cache.get("company").companyName}}</h2>

Edit object of an array using Vue.JS

I am developing my first app using Vuejs + Laravel and I am facing a problem that I couldn't solve until now!
I have an array of object and I need to edit a single of then without delete and add a new one! I have made a JS Bin to show what I need!
JS Bin
When you click in EDIT and start to typing your new value the original value edits as well but I need to change the original value only after the user hit the save button!
Anybody can help me?
PS: I will update my database and then show the new value on the table!
Is there anyway to duplicate my record as I do on the edit function without sync then?
JS
new Vue({
el: 'body',
data: {
cache: {},
record: {},
list: [
{ name: 'Google', id: 1 },
{ name: 'Facebook', id: 2 },
],
},
methods: {
doEdit: function (record) {
this.cache = record;
},
edit: function (record) {
this.record = _.cloneDeep(record);
this.cache = record;
}
}
});
HTML
<div class="container">
<form class="form-horizontal" #submit.prevent="doEdit(record)">
<div class="row">
<div class="col-md-12">
<label>Name</label>
<input type="text" class="form-control" v-el:record-name v-model="record.name">
</div>
<div class="col-xs-12" style="margin-top:15px">
<button type="submit" class="col-xs-12 btn btn-success">Save</button>
</div>
</div>
</form>
<hr>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="r in list">
<td class="text-center" style="width:90px"> {{ r.id }} </td>
<td> {{ r.name }} </td>
<td class="text-center" style="width:90px">
<span class="btn btn-warning btn-xs" #click="edit(r)"><i class="fa-fw fa fa-pencil"></i></span>
</td>
</tr>
</tbody>
</table>
</div>
You can replace the old object with the cloned-updated one.
doEdit: function (record) {
var index = _.indexOf(this.list, this.cache);
this.list.splice(index, 1, record);
}
https://jsbin.com/ruroqu/3/edit?html,js,output
If you want to save the value only after user submitted, you should not bind the record directly such as v-model="record.name".
And we can use Vue.set to change attributes of the original record.
Let's try: JS Bin

How to get JSON with Angular JS

I am trying to get my table filled with data. The url gives json back, but I don't know how to call json in angular.
This my my services.js:
angular.module('OrganisatieApp.services', [])
.factory('organisatieAPIservice', function($resource) {
var organisatieAPIservice = [];
organisatieAPIservice.getOrganisaties = function(){
return $http({
method: 'JSON_CALLBACK',
url: 'http://jbossews-themaopdracht78.rhcloud.com/rest/json/org/Organisaties'
});
}
return organisatieAPIservice;
})
controller.js :
angular.module('OrganisatieApp.controllers', []).
controller('organisatieController',function($scope, organisatieAPIservice) {
$scope.organisatieList = [];
organisatieAPIservice.getOrganisaties().success(function (response) {
//Assign response in Callback
$scope.organisatieList = response();
});
});
app.js:
angular.module('OrganisatieApp', [
'OrganisatieApp.controllers',
'OrganisatieApp.services' ]);
My html div :
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Organisatie naam</th>
<th>Organisatie plaats</th>
<th>Organisatie Curriculum</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="organisatie in organisatieList">
<td>{{$index + 1}}</td>
<td>
<img src="/img/logos/{{organisatie.Organisatie.logo}}.png" />
{{organisatie.Organisatie.orgNaam}} {{organisatie.Organisatie.orgVolledig}}
</td>
<td>{{organisatie.Constructors[0].provincie}}</td>
<td>{{organisatie.curriculum}}</td>
</tr>
</tbody>
</table>
<ng-view></ng-view>
</div>
</div>
</div>
<div class="col-md-6">
<div class="page-header">
<h1>Opleidingsprofiel</h1>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<ul class="nav nav-pills" role="tablist">
<li role="presentation">Aantal Organisaties<span class="badge">3</span></li>
</ul>
</h3>
</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Organisatie naam</th>
<th>Organisatie plaats</th>
<th>Organisatie Curriculum</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="organisatie in organisatieList">
<td>{{$index + 1}}</td>
<td>
<img src="/img/logos/{{organisatie.Organisatie.logo}}.png" />
{{organisatie.Organisatie.orgNaam}} {{organisatie.Organisatie.orgVolledig}}
</td>
<td>{{organisatie.Constructors[0].provincie}}</td>
<td>{{organisatie.curriculum}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
What am I doing wrong? I know that i am trying to call jsonp but how do I call for json.
Seems like there are couple of problem with your code.
Your jsonp call url must have callback parameter with value JSON_CALLBACK like callback=JSON_CALLBACK & its should be of type jsonp.
Code
return $http.jsonp({'http://jbossews-themaopdracht78.rhcloud.com/rest/json/org/Organisaties?callback=JSON_CALLBACK'});
OR
return $http({
method: 'jsonp',
url: 'http://jbossews-themaopdracht78.rhcloud.com/rest/json/org/Organisaties?callback=JSON_CALLBACK'
});
You should do change $scope.organisatieList = response(); to $scope.organisatieList = response; because the response contains a data.
organisatieAPIservice.getOrganisaties().success(function (response) {
//Assign response in Callback
$scope.organisatieList = response;
});
In this line, just add the "$http" as a dependency of your service, like this:
angular.module('OrganisatieApp.services', [])
.factory('organisatieAPIservice', function($resource,$http) {
//your code here
You need to add this to be able to send the request, otherwise for angular the $http variable is not defined (or imported as a dependency). And yes, like #pankajparkar and #vishnu say, you need to change in your controller this line:
$scope.organisatieList = response();
For this one:
$scope.organisatieList = response;

Categories

Resources