Hi I am trying to display my data but when i tried to display it on my html using angular data wont pass through. checked the console and data was there. here is my html.
<ion-view view-title="">
<ion-content>
<!-- <div class="cards">
<div class="item item-image">
<img src="img/banner-children.jpg"></img>
</div>
</div> -->
<div class="list card padding" ng-repeat="charity in charityList">
<a href="#/app/charitypage/{{charity.charity_id}}" class="positive ">
<img class="char-logo img-thumb" ng-src="{{charity.logo}}">
<div class="char-info">
<h3 class="char-name text-pink">
<i class="ion-chevron-right text-pink btn-category"></i>
{{charity.charity_name}}</h3>
<p class="dark">{{charity.description}}</p>
</div>
</a>
</div>
</ion-content>
and here is my controller
angular.module('subCategory.controllers', [])
.controller('subCatCtrl', function($scope, $state, $http) {
$scope.getCategoryList = function(category){
$scope.charityList = {};
var categoryListData = {
charityCategory : category
}
$http({
method: 'POST',
header: {'Content-Type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/filantrome/Main/getCategoryList',
data: categoryListData
}).then(
function success( response ) {
$scope.charityList= response.data;
console.log($scope.charityList);
$state.go('app.subcat');
},
function error( response ) {
$scope.charityList = response.data;
console.log($scope.charityList);
// handle error
}
);
console.log($scope.charityList);
};
});
i can see the data that i was requesting on the console.log() inside the success function. but when i get out of the .then(); function $scope.charityList is empty.
what am i missing here? thanks!
Seems problem is in state change. To fix this you can use service to store received JSON
angular.module('subCategory.controllers', []).service(charityService, charityService);
/* #ngInject */
function charityService($http) {
var charityList = [];
var service = {
getData: getData,
getCharityList: getCharityList
};
return service;
function getCharityList() {
return charityList ;
}
function getData(categoryListData) {
$http({
method: 'POST',
header: {'Content-Type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/filantrome/Main/getCategoryList',
data: categoryListData
}).then(
function success( response ) {
charityList = response.data;
console.log(charityList );
$state.go('app.subcat'); // you can also change state here
},
function error( response ) {
$scope.charityList = response.data;
console.log($scope.charityList);
// handle error
}
);
}
}
then post data with controller function
$scope.getCategoryList = function(category){
var categoryListData = {
charityCategory : category
}
charityService.getData(categoryListData);
}
after state changes controller will get charityList from service
angular.module('subCategory.controllers', []) .controller('subCatCtrl',
function($scope, $state, $http, charityService) {
$scope.charityList = charityService.getCharityList();
// ...
As you have posted your console.log output, I can see that you have a single object receiving and assigning to charityList but you have an ng-repeat on the element. So, I think you should change $scope.charityList = {}; to $scope.charityList = []; or you can output this variable in the html to see whats going on like {{charityList}}.
Related
I have a controller that returns an array from my django view, i am trying to display each object in a different line in my html but it just returns json.
my controller.js
mainApp.controller('hsController', function($scope, $http, $compile, $timeout, $location) {
$scope.data = {};
$scope.init = function() {
console.log("angular loaded!")
}
$scope.data.form = {
hs_search: "",
result: {},
};
$scope.data.formStyle = {
hs_search: ""
};
$scope.submitForm = function() {
//console.log($scope.data.form)
var error = 0;
if(!$scope.data.form.hs_search) {
$scope.data.formStyle.hs_search = "is_invalid";
error++;
} else {
$scope.data.formStyle.hs_search = "";
}
if(error==0) {
var jsonCall = $http({
method: 'POST',
url:'/theapp/hs-code-search',
data: $scope.data.form,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
jsonCall.success(function(data, status, headers, config) {
if(data.status==1) {
$scope.data.form.result = data.data
console.log($scope.data.form.result)
}
});
jsonCall.error(function(data, status, headers, config) {
if(data.status==0) {
$.growl.error({ message: data.error});
}
});
console.log($scope.data.form)
} else {
$.growl.error({ message: "Please fill the form correctly!"});
}
}
});
my html
<div class="row">
<div class="col-lg-11 col-md-11 mx-auto">
<h3>Search Result For </h3>
<div ng-repeat="chapter_code in data.form.result">
{[{chapter_code}]}
</div>
<div ng-repeat="chapter_desc in data.form.result">
{[{chapter_desc}]}
</div>
</div>
</div>
Result that am getting
What i wanted instead is just the value of each object shown.
Try to convert the JSON to an Object using JSON.parse() and then you can use ng-repeat
myController.js
if(data.status==1) {
$scope.data.form.result = JSON.parse(data.data);
console.log($scope.data.form.result);
// Console shall return an Object
}
HTML
<div class="row">
<div class="col-lg-11 col-md-11 mx-auto">
<h3>Search Result For </h3>
<div ng-repeat="chapterCode in data.form.result.chapter_code">
{{chapterCode}}
</div>
<div ng-repeat="chapterDesc in data.form.result.chapter_desc">
{{chapterDesc}}
</div>
</div>
</div>
Ok so there is a lot out there about sharing data between controllers using factory/service, but I'm not finding what applies to my issue. Either I'm interpreting the answers incorrectly or this is a valid question I'm about to ask! Hopefully the latter.
I would like controller 2 to recognize when a new http call has been made and the factory images object has been updated. at the moment it resolves once and then ignores any subsequent updates. What am i overlooking?
My view:
<div>
<ul class="dynamic-grid" angular-grid="pics" grid-width="150" gutter-size="0" angular-grid-id="gallery" refresh-on-img-load="false" >
<li data-ng-repeat="pic in pics" class="grid" data-ng-clock>
<img src="{{pic.image.low_res.url}}" class="grid-img" data-actual-width = "{{pic.image.low_res.width}}" data-actual-height="{{pic.image.low_res.height}}" />
</li>
</ul>
</div>
factory:
.factory('imageService',['$q','$http',function($q,$http){
var images = {}
var imageServices = {};
imageServices.homeImages = function(){
console.log('fire home images')
images = $http({
method: 'GET',
url: '/api/insta/geo',
params: homeLoc
})
};
imageServices.locImages = function(placename){
console.log('fire locImages')
images = $http({
method: 'GET',
url: '/api/geo/loc',
params: placename
})
};
imageServices.getImages = function(){
console.log('fire get images', images)
return images;
}
return imageServices;
}]);
controller1:
angular.module('trailApp.intro', [])
.controller('introCtrl', function($scope, $location, $state, showTrails, imageService) {
// run the images service so the background can load
imageService.homeImages();
var intro = this;
intro.showlist = false;
intro.data = [];
//to get all the trails based on user's selected city and state (collected in the location object that's passed in)
intro.getList = function(location) {
intro.city = capitalize(location.city);
intro.state = capitalize(location.state);
//get placename for bg
var placename = {placename: intro.city + ',' + intro.state};
imageService.locImages(placename);
... do other stuff...
controller2:
angular.module('trailApp.bkgd', [])
.controller('bkgdCtrl', ['$scope','imageService', 'angularGridInstance', function ($scope,imageService, angularGridInstance) {
$scope.pics = {};
imageService.getImages().then(function(data){
$scope.pics = data;
console.log($scope.pics);
});
}]);
Your controller2 implementation only got the images once, you probably need a $watch to keep to updated:
angular.module('trailApp.bkgd', [])
.controller('bkgdCtrl', ['$scope','imageService', 'angularGridInstance', function ($scope,imageService, angularGridInstance) {
$scope.pics = {};
$scope.$watch(function(){
return imageService.getImages(); // This returns a promise
}, function(images, oldImages){
if(images !== oldImages){ // According to your implementation, your images promise changes reference
images.then(function(data){
$scope.pics = data;
console.log($scope.pics);
});
}
});
}]);
I am using AngularJs to retrieve the data from ASP.Net Controller.
The Json data is retrieved from the server, but can't figure out why cannot display array items when using the ng-repeat:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$http({ method: 'GET', url: '/home/listvalues?listid=3' }).then(function (response) {
$scope.lookupItems = response;
console.log($scope.lookupItems);
},
function (error) { alert("error"); });
// console.log($scope.listItems);
});
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
The Json Retrieved from the server:
[{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}]
The most likely issue (assuming that your app and controller are constructed and referenced properly) is that the object returned from the promise contains a .data property which actually holds your JSON data.
Try this:
$http({ method: 'GET', url: '/home/listvalues?listid=3' })
.then(function (response) {
$scope.lookupItems = response.data;
console.log($scope.lookupItems);
},
function (error) {
alert("error");
});
I think you just forgot to wrap your app with ng-app:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$scope.lookupItems = [{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}];
console.log($scope.lookupItems);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="Appp">
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
</body>
You probably misspelled Appp. Make sure your module definition in your javascript:
var app = angular.module('App', []); //Changed to App from Appp
matches your app declaration in your html
<div ng-app="App">
...controller declaration...
...body.....
</div>
Sorry for a very stupid question but I just started working with AngularJS and OnsenUI.
I have got a service to get a data from SQLite:
module.factory('$update', function () {
var update = {};
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM event_updates', [], function (tx, results) {
var rows = results.rows;
update.items = [];
if (!rows.length) {} else {
for (var index = 0; index < rows.length; index++) {
update.items.push({
"title": rows.item(index).title,
"date": rows.item(index).date,
"desc": rows.item(index).desc
});
}
}
}, function (error) {
console.log(error);
});
});
return update;
});
And a controller which is using the data:
module.controller('UpdatesController', function ($scope, $update) {
$scope.items = $update.items;
});
As soon as my page is loaded the content is not displayed and I need to click twice to call a page with the code below to see the content:
<ons-list ng-controller="UpdatesController">
<ons-list-item modifier="chevron" class="list-item-container" ng-repeat="item in items" ng-click="showUpdate($index)">
<div class="list-item-left">
</div>
<div class="list-item-right">
<div class="list-item-content">
<div class="name">{{item.title}}</div> <span class="desc">{{item.desc}}</span>
</div>
</div>
</ons-list-item>
</ons-list>
Can anybody help how can I initialise the controller as soon as page is loaded with all content. Sorry if it is a stupid question but I am really struggling. Appreciate your help a lot.
You could store the result of the request in the factory and retrieve those instead.
module.factory('$update', function () {
var update = {};
var requestValues = function(){ // store the results of the request in 'update'
// Your db.transaction function here
}
var getUpdates = function(){ // retrieve the values from 'update'
return update;
}
return{
requestValues : requestValues,
getUpdates : getUpdates
}
});
And then in you controller:
module.controller('UpdatesController', function ($scope, $update) {
$update.requestValues();
$scope.items = $update.getUpdates();
});
You could then get the values from anywhere in you solution (by using $update.getUpdates) without having to make an extra http request.
Objective: Two Way Databinding between database and view via scope and controller
I’m trying to post to a restful database using angular
When I click on the thumbs up or thumbs down the scope changes o.k and is reflected in the view
However how can this placed in real time to a restful database using http post ?
Here’s the HTML
<div ng-controller="ordersCtrl">
<div class="span0 well votingWidget">
<div class="votingButton" ng-click="upVoteOrder(order)">
<i class="icon-thumbs-up "></i>
</div>
<div class="badge ">
<div>{{order.upVoteCount}}</div>
</div>
<div class="votingButton" ng-click="downVoteOrder(order)">
<i class="icon-thumbs-down"></i>
</div>
Heres the Controller: My issue lies here in the http.post command
.controller("ordersCtrl", function ($scope, $http, ordersUrl) {
$scope.downVoteOrder = function(order) {
$scope.selectedOrder = order;
order.upVoteCount--;
$http.post(orderUrl, order.upVoteCount)
.success(function (data) {
$scope.data.orderupVoteCount = data.id;
})
};
});
Note : I can post form data to the restful database successfully using the following code
$scope.sendOrder = function (shippingDetails) {
var order = angular.copy(shippingDetails);
order.products = cart.getProducts();
$http.post(orderUrl, order)
.success(function (data) {
$scope.data.orderId = data.id;
cart.getProducts().length = 0;
})
.error(function (error) {
$scope.data.orderError = error;
}).finally(function () {
$location.path("/uploaded");
});
}
you should use a separate service to handle the http post .
var app = angular.module("myApp", []);
app.factory("OrderService", ["$http", function ($http) {
this.PostDownVote = function(orderUrl, upVoteCount) {
return $http.post(orderUrl, upVoteCount);
}
this.PostOrder = function(orderUrl, order) {
// do something
}
return this;
}]);
Now inject this OrderService to you controller and use it.
app.controller("ordersCtrl", function ($scope, $http, ordersUrl, OrderService) {
$scope.downVoteOrder = function(order) {
$scope.selectedOrder = order;
order.upVoteCount--;
OrderService.PostDownVote(ordersUrl, order.upVoteCount)
.success(data) {// do something}
.error(data) {// do something}
}
});