how to fetch Data from API using Angular js - javascript
I am working on a project where I need to fetch data from API and display it on HTML page using Angularjs
API is returning me the Categories details. Here is my API
http://naazexpress.com/category.php
this is my angularjs Code
var app = angular.module('appControllers', [])
app.controller('ProductCtrl', function($scope, srvShareData,$http) {
// alert('product Controller');
$http.get("http://naazexpress.com/category.php")
.then(function (response) {
$scope.data = response.data.children;
console.log(response);
});
console.log('aa');
// alert($scope.data);
$scope.sharedData = srvShareData.getData();
console.log($scope.sharedData);
});
app.service('srvShareData', function($window) {
var KEY = 'App.SelectedValue';
// alert('ssss');
var addData = function(newObj) {
var mydata = $window.sessionStorage.getItem(KEY);
console.log(mydata);
if (mydata) {
mydata = JSON.parse(mydata);
} else {
mydata = [];
}
mydata = newObj;
console.log(mydata);
// mydata.push(newObj);
$window.sessionStorage.setItem(KEY, JSON.stringify(mydata));
};
var getData = function(){
var mydata = $window.sessionStorage.getItem(KEY);
if (mydata) {
mydata = JSON.parse(mydata);
}
return mydata || [];
};
return {
addData: addData,
getData: getData
};
});
and I am implementing it in my HTML page
here is my HTML page
<div id="login-page" class="row" ng-app="starter">
<div class="col s12 z-depth-6 card-panel">
<form class="login-form" id="login">
<div class="row">
<div class="input-field col s12 center">
<img src="http://naazexpress.com/skin/frontend/default/jm_casual/images/logo.png" alt="" class="responsive-img valign profile-image-login">
<p class="center login-form-text">Seller - NaazExpress</p>
</div>
</div>
<div class="input-field col s12 m6" ng-controller="ProductCtrl">
<ul ng-repeat="item in data">
<li>{{item.name}}</li>
</ul></div>
</div></div>
when i run this program the API is not returning anything. is there any issue in the code ? please help
Try This.
$http.get("http://naazexpress.com/category.php")
.then(function (response) {
$scope.data = response.data.children;
console.log(response.data);
});
Your response doesn't have property "children"
Here is the response, it has property "category" and then this "category" has "children"
{"category":{"category_id":"1","parent_id":"0","name":"Root Catalog","is_active":null,"position":"0","level":"0","children":[{"category_id":"2","parent_id":"1","name":"Default Category","is_active":"1","position":"1","level":"1","children":[{"category_id":"3","parent_id":"2","name":"New arrivals","is_active":"1","position":"1","level":"2","children":[{"category_id":"10","parent_id":"3","name":"New","is_active":"1","position":"2","level":"3","children":[]},{"category_id":"11","parent_id":"3","name":"Tops","is_active":"1","position":"3","level":"3","children":[]},{"category_id":"12","parent_id":"3","name":"Bottoms","is_active":"1","position":"4","level":"3","children":[]},{"category_id":"13","parent_id":"3","name":"Denim","is_active":"1","position":"5","level":"3","children":[]},{"category_id":"14","parent_id":"3","name":"Outerwear","is_active":"1","position":"6","level":"3","children":[]},{"category_id":"15","parent_id":"3","name":"Shoes","is_active":"1","position":"7","level":"3","children":[]},{"category_id":"16","parent_id":"3","name":"Jackets","is_active":"1","position":"8","level":"3","children":[]},{"category_id":"17","parent_id":"3","name":"Accessories","is_active":"1","position":"9","level":"3","children":[]}]},{"category_id":"4","parent_id":"2","name":"Women","is_active":"1","position":"2","level":"2","children":[{"category_id":"18","parent_id":"4","name":"New","is_active":"1","position":"1","level":"3","children":[]},{"category_id":"19","parent_id":"4","name":"Tops","is_active":"1","position":"2","level":"3","children":[]},{"category_id":"20","parent_id":"4","name":"Bottoms","is_active":"1","position":"3","level":"3","children":[]},{"category_id":"21","parent_id":"4","name":"Denim","is_active":"1","position":"4","level":"3","children":[]},{"category_id":"22","parent_id":"4","name":"Outerwear","is_active":"1","position":"5","level":"3","children":[]},{"category_id":"23","parent_id":"4","name":"Shoes","is_active":"1","position":"6","level":"3","children":[]},{"category_id":"24","parent_id":"4","name":"Jackets","is_active":"1","position":"7","level":"3","children":[]},{"category_id":"25","parent_id":"4","name":"Accessories","is_active":"1","position":"8","level":"3","children":[]}]},{"category_id":"5","parent_id":"2","name":"Men","is_active":"1","position":"3","level":"2","children":[]},{"category_id":"6","parent_id":"2","name":"Accessories","is_active":"1","position":"4","level":"2","children":[]},{"category_id":"7","parent_id":"2","name":"Sale","is_active":"1","position":"5","level":"2","children":[]},{"category_id":"26","parent_id":"2","name":"Men2","is_active":"1","position":"6","level":"2","children":[]}]}]}}
So try this
response.data.category.children;
Related
precheck checkboxes depending on the response coming in json form in vuejs
Sorry for my English. I am trying to pre select those checkboxes whos values have been saved in the database. I did it using javascript in vuejs but those selected checkboxes values are not storing in array. My code is like role.component.js getRoleRowData(data) { this.roleaction = "edit"; this.addrolemodal = true; console.log(data.role_id); axios .post(apiUrl.api_url + "getRolePermissionData", { role_id: data.role_id }).then( result => { this.permid = result.data; var list = []; result.data.forEach(function(value) { list.push(value.perm_id); }); var options = list; for (var i = 0; i < options.length; i++) { if (options[i]) document.querySelectorAll('input[value="' + options[i] + '"][type="checkbox"]')[0].checked = true; } }, error => { console.error(error); } ); this.addrole = data; }, And role.component.html <div class="col-md-8"> <b-form-fieldset> <div class="form" id="demo"> <h6>Permissions</h6> <span v-for="perm_name_obj in listPermissionData"> <input type="checkbox" class="perm_id" v-bind:value="perm_name_obj.perm_id" name="perm_id" id="perm_name" v-model="checkedPerm_Id"> {{perm_name_obj.perm_name}}<br> </span> <span>Checked names: {{ checkedPerm_Id }}</span> </div> </b-form-fieldset> </div> And the Output And the Ouput I got In simple words I want to pre check checkboxes in vuejs of which values are stored in database.
See the following example, using simulation data var app = new Vue({ el: '#app', data () { return { listPermissionData: [], checkedPerm_Id: [] } }, created () { setTimeout(_=>{ //Here simulates axois to request Permission data this.listPermissionData = [ {perm_id:1,perm_name:'perm_name1'}, {perm_id:2,perm_name:'perm_name2'}, {perm_id:3,perm_name:'perm_name3'}, {perm_id:4,perm_name:'perm_name4'}, {perm_id:5,perm_name:'perm_name5'} ]; //Here simulates axois to request Selected Permissions (result.data) var selected = [ {perm_id:2,perm_name:'perm_name2'}, {perm_id:5,perm_name:'perm_name5'} ] this.checkedPerm_Id = selected.map(o=>o.perm_id) },1000) } }) <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <div class="form"> <h6>Permissions</h6> <span v-for="perm_name_obj in listPermissionData"> <input type="checkbox" class="perm_id" v-bind:value="perm_name_obj.perm_id" name="perm_id" id="perm_name" v-model="checkedPerm_Id"> {{perm_name_obj.perm_name}}<br> </span> <span>Checked names: {{ checkedPerm_Id }}</span> </div> </div>
I solved my problem, here is my code role.component.js getRoleRowData(data) { this.roleaction = "edit"; this.addrolemodal = true; console.log(data.role_id); let tempthis = this; axios .post(apiUrl.api_url + "getRolePermissionData", { role_id: data.role_id }).then( result => { this.permid = result.data; var list = []; result.data.forEach(function(value) { //by using tempthis variable we provided the current access to the checkedPerm_Id array which not accessible from out of the function which is getRoleRowData tempthis.checkedPerm_Id.push(value.perm_id); list.push(value.perm_id); }); }, error => { console.error(error); } ); this.addrole = data; },
Vue loop list - append the ajax returned data into the list?
How can I append vue list after ajax call? This is my HTML with Vue: Load More <div id="news-posts"> <!-- item --> <template v-for="item in items"> <div class="cell large-4 medium-6"> <!-- image has no padding --> <div class="card grid-item"> <div class="card-divider"> <h4 class="heading heading-card"><a :href=item.url><span v-html=item.title></span></a></h4> </div> <div class="card-date"> <span v-html=item.date></span> </div> <div class="card-section"><p v-html=item.excerpt></p></div> <div class="text-right"> <a :href=item.url class="button button-more"><i class="material-icons">chevron_right</i></a> </div> </div> </div> <!-- item --> </template> <!-- vue - loop --> </div> Js: // Render template with Vue. // Get json of catering menu. var element = document.getElementById('news-posts') var buttonLoad = document.getElementById('button-load') if (element !== null) { // var endpoint = $('#button-load').data('posts-endpoint') // jQuery var endpoint = buttonLoad.getAttribute('data-posts-endpoint') // Vanilla JS var getData = await axios.get(endpoint) var cateringMenu = new Vue({ el: '#news-posts', data: { items: getData.data } }) } $("#button-load").click(function(){ var endpoint = buttonLoad.getAttribute('data-posts-endpoint') // Vanilla JS $.get(endpoint, function(data, status){ var cateringMenu = new Vue({ el: '#news-posts', data: { items: data } }) }) return false }) Of course, it does not append the ajax returned data into the list. Any idea? EDIT: Got it working with: methods: { fetch: function (event) { var self = this // `this` inside methods points to the Vue instance $.ajax({ url: endpoint, method: 'GET', success: function (data) { data.map(function(item) { self.items.push(item) }) }, error: function (error) { console.log(error) } }) } }
Have you tried to make your button execute a method that is defined in Vue, so you have access to the instance and can set the items with this, something like this; methods: { fetch: function(){ var endpoint = buttonLoad.getAttribute('data-posts-endpoint'); $.get(endpoint, function(data, status){ this.items = data; //set items. }) } } and then add the fecth method to your button (needs to be in the vue wrapper, its outside at the moment it looks like) v-on:click.prevent="this.fecth"
Why is angularJS not binding data?
I'm fetching maximum salary from Employee table. The JSON retrieves the data properly but why angular does not bind data? Controller.js app.controller('AdminCntrl', function ($scope, AdminServices) { $scope.BtnSubmit = function () { alert('ok1') var Bust = AdminServices.Getmax(); Bust.then(function (d) { $scope.Emp = d.data; }) } }) Service.js app.service('AdminServices', function ($http) { this.Getmax = function () { var ss = $http({ url: '/Department/Max', method: 'Get', data:JSON.stringify(), content:{'content-type' : 'application/Json'} }) return ss; } }) Controller public JsonResult Max() { var xxx = db.Employees.OrderByDescending(ww => ww.Salary).First(); return new JsonResult { Data = xxx, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } Emp.cshtml <div ng-controller="AdminCntrl"> <input type="button" class="btn btn-primary btn-sm" value="Min" ng-click="BtnSubmit()" /> <div ng-repeat="Accessor in Emp"> {{Accessor.Id}} <span style="color:red">{{Accessor.Name}}</span> </div> </div> Fiddler Catch Data {"Id":11,"Name":"Saleem","Department":"Oracle","Salary":100000.00,"EmpType":"Admin","DataofJoin":"\/Date(1462127400000)\/","DataofBirth":"\/Date(597868200000)\/"}
Is the value of $scope.Empequal to your Fiddler Data? It appears you're not returning an array which is what ng-repeat is expecting. I'd bet if your Fiddler data was represented as an array: [{"Id":11,"Name":"Saleem","Department":"Oracle","Salary":100000.00,"EmpType":"Admin","DataofJoin":"\/Date(1462127400000)\/","DataofBirth":"\/Date(597868200000)\/"}] you'd see it bind. Alternatively, if you're really not expecting an array then if you replace <div ng-repeat="Accessor in Emp"> {{Accessor.Id}} <span style="color:red">{{Accessor.Name}}</span> </div> with: <div> {{Emp.Id}} <span style="color:red">{{Emp.Name}}</span> </div> You'd have some success
angularJs, I'm not succeeding set view refresh after data get from ajax call
I've searched a lot before answer this question and couldn'y find any solution working for me. I've started studying angular and I've been able to create a simple page with an ng-repeat that iter an object. The next step I want to achieve is to update this object from an AJAX call to an API. The problem is that I'm not able to do this. It seems to me that the problem is the function inside the controller: is not able to edit an attribute of the same controller: app.controller('StoreController', [ '$http', 'ajaxFactory', function($http, ajaxFactory) { this.products = products; this.getProducts = function() { /* this works and empty the object AND the view on the click */ this.products = []; ajaxFactory.getFamily2().then(function(data) { /* * this DOES NOT works, DOES NOT empty the object NOR the * view on the click */ /* * i'm sure the AJAX call is working, i can see the result * and also alert his content */ this.products = data; }); }; } ]); Thanks in advance FULL CODE: Html: <div ng-app="catalogo"> <div ng-controller="StoreController as store"> <!-- *** Store Header *** --> <header class="text-center"> <h3>– an Angular catalogue –</h3> </header> <!-- *** Products Container *** --> <div class="container" ng-controller="TotalPriceController as total"> <div class="row"> <!-- Product Container --> <div class="col col-xs-4" ng-repeat="(key,product) in store.products" ng-class="{ hero: key%2 === 0 }"> <div class="row"> <product-title></product-title> </div> <div class="row"> <!-- Image Gallery --> <product-gallery></product-gallery> </div> <div class="row"> <!-- Product Tabs --> <product-calculate></product-calculate> </div> <div class="row"> <!-- Product Tabs --> <product-tabs></product-tabs> </div> </div> </div> <div class="row"> <button ng-click="store.getProducts()">Kliq Here!</button> <product-total></product-total> </div> </div> </div> JS: (function() { var app = angular.module('catalogo', [ 'store-directives' ]); app.factory('ajaxFactory', function($http) { var factory = {}; factory.getFamily2 = function() { return $http.get("http://apigility-ds.gsanet.it/rpc").then( function(result) { return result.data; }); } return factory; }); app.controller('TotalPriceController', function() { this.totalPrice = 0; this.calculateTotalPrice = function() { this.totalPrice = 0; for ( var x in products) { var product = products[x]; if (typeof (product.num) !== 'undefined') { this.totalPrice += (product.price * product.num); } } }; }); app.config(function($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; }); app.controller('StoreController', [ '$http', 'ajaxFactory', function($http, ajaxFactory) { this.products = products; this.getProducts = function() { this.products = []; ajaxFactory.getFamily2().then(function(data) { this.products = data; }); }; } ]); app.controller('ReviewController', function() { this.review = {}; this.addReview = function(product) { product.reviews.push(this.review); this.review = {}; }; }); var products = [ { name : 'Ballons', price : 7.99, description : "A lot of colored ballons", images : [ "../img/balloons.jpg", "../img/balloons2.jpg" ], specs : { number : 10, color : 'various' }, reviews : [] }, { name : 'Cards', price : 3.99, description : "wonderful set of cards.", images : [ "../img/cards.jpg", "../img/cards2.jpg" ], specs : { type : 'poker deck', cards : 52 }, reviews : [] }, { name : 'Watch', price : 159.99, description : "An awesome watch, make you so cool.", images : [ "../img/watchmaker.jpg", "../img/watchmaker2.jpg" ], specs : { color : 'black', year : '2014', brand : 'SWATCH' }, reviews : [] } ]; })();
You are having invalid reference to this.products from closure(It doesn't refere to this.products declared outside the getProducts function). You can correct it like this app.controller('StoreController', [ '$http', 'ajaxFactory', function($http, ajaxFactory) { var controller = this; controller.products = products; controller.getProducts = function() { /* this works and empty the object AND the view on the click */ controller.products = []; ajaxFactory.getFamily2().then(function(data) { /* * this DOES NOT works, DOES NOT empty the object NOR the * view on the click */ /* * i'm sure the AJAX call is working, i can see the result * and also alert his content */ controller.products = data; }); }; } ]); Between you can also have a look on angular services to make your code more robust and easier to test.
Node/AngularJS - TypeError: Cannot read property '_id' of undefined.
I am new to the MEAN and i am trying to make a simple CRUD application. I am getting an error of undefined on my _id and i do not understand why. This variable works withevery other function I call it in. Hopefully someone can help. I am getting the error on line 117 in my controller.js file Here is the controller.js code for my application todoApp.controller('TodoCtrl', function($rootScope, $scope, todosFactory) { $scope.todos = []; $scope.isEditable = []; // get all Todos on Load todosFactory.getTodos().then(function(data) { $scope.todos = data.data; }); // Save a Todo to the server $scope.save = function($event) { if ($event.which == 13 && $scope.todoInput) { todosFactory.saveTodo({ "todo": $scope.todoInput, "isCompleted": false }).then(function(data) { $scope.todos.push(data.data); }); $scope.todoInput = ''; } }; //update the status of the Todo $scope.updateStatus = function($event, _id, i) { var cbk = $event.target.checked; var _t = $scope.todos[i]; todosFactory.updateTodo({ _id: _id, isCompleted: cbk, todo: _t.todo }).then(function(data) { if (data.data.updatedExisting) { _t.isCompleted = cbk; } else { alert('Oops something went wrong!'); } }); }; // Update the edited Todo $scope.edit = function($event, i) { if ($event.which == 13 && $event.target.value.trim()) { var _t = $scope.todos[i]; todosFactory.updateTodo({ _id: _t._id, todo: $event.target.value.trim(), isCompleted: _t.isCompleted }).then(function(data) { if (data.data.updatedExisting) { _t.todo = $event.target.value.trim(); $scope.isEditable[i] = false; } else { alert('Oops something went wrong!'); } }); } }; // Delete a Todo $scope.delete = function(i) { todosFactory.deleteTodo($scope.todos[i]._id).then(function(data) { if (data.data) { $scope.todos.splice(i, 1); } }); }; }); todoApp.controller('TodoCtrl', function($rootScope, $scope, todosFactory) { $scope.todos = []; $scope.isEditable = []; // get all Todos on Load todosFactory.getTodos().then(function(data) { $scope.todos = data.data; }); // Save a Todo to the server $scope.save = function($event) { if ($event.which == 13 && $scope.todoInput) { todosFactory.saveTodo({ "todo": $scope.todoInput, "isCompleted": false }).then(function(data) { $scope.todos.push(data.data); }); $scope.todoInput = ''; } }; //update the status of the Todo $scope.updateStatus = function($event, _id, i) { var cbk = $event.target.checked; var _t = $scope.todos[i]; todosFactory.updateTodo({ _id: _id, isCompleted: cbk, todo: _t.todo }).then(function(data) { if (data.data.updatedExisting) { _t.isCompleted = cbk; } else { alert('Oops something went wrong!'); } }); }; // Update the edited Todo $scope.edit = function($event, i) { if ($event.which == 13 && $event.target.value.trim()) { var _t = $scope.todos[i]; todosFactory.updateTodo({ _id: _t._id, todo: $event.target.value.trim(), isCompleted: _t.isCompleted }).then(function(data) { if (data.data.updatedExisting) { _t.todo = $event.target.value.trim(); $scope.isEditable[i] = false; } else { alert('Oops something went wrong!'); } }); } }; // Delete a Todo $scope.delete = function(i) { todosFactory.deleteTodo($scope.todos[i]._id).then(function(data) { if (data.data) { $scope.todos.splice(i, 1); } }); }; }); Just is case the error is in either my factory.js code or html, I will include both. Here is the factory.js code: todoApp.factory('todosFactory', function($http){ var urlBase = '/api/todos'; var _todoService = {}; _todoService.getTodos = function(){ return $http.get(urlBase); }; _todoService.saveTodo = function(todo){ return $http.post(urlBase, todo); }; _todoService.updateTodo = function(todo) { return $http.put(urlBase, todo); }; _todoService.deleteTodo = function(id){ return $http.delete(urlBase + '/' + id); }; return _todoService; }); Here the html partial that uses the controller and factory: <div class="container" ng-controller="TodoCtrl"> <div class="row col-md-12"> <div> <input type="text" class="form-control input-lg" placeholder="Enter a todo" ng-keypress="save($event)" ng-model="todoInput"> </div> </div> <div class="row col-md-12 todos"> <div class="alert alert-info text-center" ng-hide="todos.length > 0"> <h3>Nothing Yet!</h3> </div> <div ng-repeat="todo in todos" class=" col-md-12 col-sm-12 col-xs-12" ng-class="todo.isCompleted ? 'strike' : ''"> <div class="col-md-1 col-sm-1 col-xs-1"> <input type="checkbox" ng-checked="todo.isCompleted" ng-click="updateStatus($event, todo._id, $index)"> </div> <div class="col-md-8 col-sm-8 col-xs-8"> <span ng-show="!isEditable[$index]">{{todo.todo}}</span> <input ng-show="isEditable[$index]" type="text" value="{{todo.todo}}" ng-keypress="edit($event)"> <input ng-show="isEditable[$index]" type="button" class="btn btn-warning" value="Cancel" ng-click="isEditable[$index] = false" /> </div> <div class="col-md-3 col-sm-3 col-xs-3" > <input type="button" class="btn btn-info" ng-disabled="todo.isCompleted" class="pull-right" value="edit" ng-click="isEditable[$index] = true" /> <input type="button" class="btn btn-danger" class="pull-right" value="Delete" ng- click="delete($index)" /> </div> </div> </div>
This line must be the cause of the issue: <input ng-show="isEditable[$index]" type="text" value="{{todo.todo}}" ng-keypress="edit($event)"> You forgot to pass the $index as the second parameter of the edit function. This should fix it: <input ng-show="isEditable[$index]" type="text" value="{{todo.todo}}" ng-keypress="edit($event, $index)">