AngularJS doesn't display json object in html after $http.get request - angularjs

I'm trying to make a get request and display the json data.
Here is the html div tag where the data should be displayed:
<div ng-app="app" ng-controller="searchController">
<ul>
<li ng-repeat="name in datas">
{{ name }}
</li>
</ul>
</div>
And here is the app:
var app = angular.module('app', [
]);
app.factory('getRequest', ($http) => {
function get() {
return $http.get('http://localhost:8080/imagedata/')
.then((response) => {
console.log(response.data);
return response.data;
},
(error) => {
return error.statusText;
});
}
return {
get: get
}
});
app.controller('searchController', ['$scope', 'getRequest', ($scope, getRequest) => {
$scope.datas = getRequest.get();
}]);
Inside factory I have a console.log. The data is shown in console, but not in html view. I can't explain what is happening. The code should be works fine.

It's a little hard to tell what the solution is without seeing your console data. If the data ('datas') displayed in your console is an array of objects, for example something like this...
[
{customerId: '123', name: 'Person1', city: "Toronto"},
{customerId: '456', name: 'Person2', city: "Los Angeles"},
{customerId: '789', name: 'Person3', city: "New York"}
]
you'll want to name the specific properties, like this..
<div ng-app="app" ng-controller="searchController">
<ul>
<li ng-repeat="item in datas">
{{item.name}} <--------------
{{item.customerId}}
{{item.city}}
</li>
</ul>
</div>

I found the solution. As #user2864740 said, in my code I've returned the promise, not a good practice. Passing a promise into ngRepeat here is the solution

Related

Add html to json content in an NG-Repeat

Im repeating objects of JSON using NG-Repeat. How do I include html, such as a link, in here:
{id: "53", description: "here is a <a href = '#/detail/'>Link</a> to something", additional: ["2.jpg", "3.jpg" ]}
You need to use $sce to trust the HTML. I like to create a filter and use ng-bind-html on a <span> tag. Using a filter makes it super simple to show HTML wherever you need. Here is a simple example.
angular.module('app', [])
.filter('unsafe', ($sce) => {
return function(value) {
return $sce.trustAsHtml(value);
}
})
.controller('ctrl', ($scope) => {
$scope.items = [{
id: "53",
description: "here is a <a href = '#/detail/'>Link</a> to something",
additional: ["2.jpg", "3.jpg"]
},
{
id: "54",
description: "here is another <a href = '#/detail/'>Link</a> to something",
additional: ["4.jpg", "5.jpg"]
}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<ul>
<li ng-repeat="item in items"><span ng-bind-html="item.description | unsafe"></span></li>
</ul>
</div>

My angular script only works when I open my html page as a static file and not when I run it with django

I've got an array inside my <script> tags and am trying to reference it in the html body:
<html ng-app="myApp">
<head>
<link rel="stylesheet" type="text/css" href="https://bootswatch.com/yeti/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('HomeController', function($scope){
this.posts = feedback;
});
app.controller('TabController', function($scope){
this.tab = 1;
this.setTab = function(newValue){
this.tab = newValue;
};
this.isSet = function(tabName){
return this.tab === tabName;
};
});
var feedback = [{
author: 'Joe Shmo',
body: 'I really love this product, no complaints',
votes: 0,
createdOn: 1397490980837,
tags: ['great', 'cool'],
people: ['Santa Clause']
},
{
author: 'Stinky Pete',
body: 'Sucky product all around',
votes: 0,
createdOn: 1397490980837,
tags: ['terrible', 'stinks'],
people: ['Tooth Fairy']
}];
</script>
</head>
<body>
<section ng-controller="TabController as tab">
<ul class="nav nav-pills nav-stacked">
<li ng-class="{ active:tab.isSet(1) }">
<a href ng-click="tab.setTab(1)">Home</a>
</li>
<li ng-class="{ active:tab.isSet(2) }">
<a href ng-click="tab.setTab(2)">Groups</a>
</li>
<li ng-class="{ active:tab.isSet(3) }">
<a href ng-click="tab.setTab(3)">Notifications</a>
</li>
<div ng-show="tab.isSet(1)" ng-controller="HomeController as home">
<h3>Home Base</h3>
<div ng-repeat="post in home.posts">
<h4>{{ post.author }} <em class="pull-right">{{ post.votes }}</em></h4>
<h5>{{ post.createdOn | date }}</h5>
<p>{{ post.body }}</p>
</div>
</div>
<div ng-show="tab.isSet(2)">
<h3>Your Groups</h3>
</div>
<div ng-show="tab.isSet(3)">
<h3>Nothing to see here.</h3>
</div>
</ul>
</section>
</body>
When I have this running in the browser, I don't get any errors, but when I click the "Home" tab, only Home Base appears and, upon inspecting the page, the <h4>, <h5> and <p> tags are all there, but they are empty. Any help would be appreciated!
FOLLOW UP: I'm using Angular1.4.9, Django1.9 with REST framework, could it be some kind of compatibility issue?
As many of the comments have said, the content is displayed when you open it as a static file, but when I have my django server going, the content does not appear.
I was able to get this to work by doing two things:
Using $scope for the "posts" var:
Replace this:
app.controller('HomeController', function($scope){
this.posts = feedback;
});
With This:
app.controller('HomeController', function($scope){
$scope.posts = feedback;
});
Next - Remove "home" from the ng-repeat here:
<div ng-controller="HomeController as home">
<h3>Home Base</h3>
<div ng-repeat="post in posts">
<h4>{{ post.author }}
<em class="pull-right">{{ post.votes }} </em></h4>
<h5>{{ post.createdOn | date }}</h5>
<p>{{ post.body }}</p>
</div>
</div>
looks like you may be using angular version 1.1.4 or below. Your code works if angular is v 1.1.5 or above. This is because Controller as syntax used in your code was introduced post 1.1.5
None working fiddle: http://jsfiddle.net/halirgb/Lvc0u55v/
This gives below error. Check your console.
Error: Argument 'TabController as tab' is not a function, got undefined
Working Fiddle: http://jsfiddle.net/Lzgts/683/
var app = angular.module('myApp', []);
app.controller('HomeController', function($scope){
this.posts = feedback;
});
app.controller('TabController', function($scope){
this.tab = 1;
this.setTab = function(newValue){
this.tab = newValue;
};
this.isSet = function(tabName){
return this.tab === tabName;
};
});
var feedback = [{
author: 'Joe Shmo',
body: 'I really love this product, no complaints',
votes: 0,
createdOn: 1397490980837,
tags: ['great', 'cool'],
people: ['Santa Clause']
},
{
author: 'Stinky Pete',
body: 'Sucky product all around',
votes: 0,
createdOn: 1397490980837,
tags: ['terrible', 'stinks'],
people: ['Tooth Fairy']
}];
Turns out it was an issue with Django and Angular. Both use the {{ }} notation so the interpreter was seeing {{ post.author }} as django and not angular. The way to fix this was to put {% verbatim %} and {% endverbatim %} at the beginning and end of my html file, and it works now!

Angular-Js unable to push data into array of controller

HTML:-
<div ng-controller="countryController">
{{name}}
<ul>
<li ng-repeat="country in countries">
{{ country.name }}
<ul ng-show="country.states.length > 0">
<li ng-repeat="state in country.states">
{{ state.name }}
</li>
</ul>
<input type="text" ng-model="newState">
<a href ng-click="addStateState(country)">Add </a>
{{newState}}
</li>
</ul>
</div>
When I key in newState model it appears in client side.
Now i try to get that value into controller and try to push in array of states, its unable to add into states array.
JS Controller:-
myApp.factory('countryService', function($http){
var baseUrl = 'services/'
return {
getCountries : function(){
return $http.get(baseUrl + 'getcountries.php');
}
};
});
myApp.controller('countryController', function($scope, countryService){
countryService.getCountries().success(function(data){
$scope.countries = data;
});
$scope.addStateState = function(country){
country.states.push({'name' : $scope.newState});
$scope.newState = "";
};
});
Your main issue is that your $scope.newState is not available inside $scope.newStateState function. It is bad practice to manipulate an object like $scope within a $scope function. In fact, you are creating multiple multiple objects that are not the same as the $scope that you inject; otherwise, the input boxes for two different countries should match.
Working Plunkr below.
http://plnkr.co/edit/HG3zWG?p=preview
JS:
angular.module('myApp',[])
.controller('countryController', function($scope){
$scope.countries = [
{ name: 'USA', states:[
{name: 'Virginia'},
{name: 'Utah'}
]
},
{ name: 'Brazil', states:[
{name: 'Pernabuco'}
]
}
];
$scope.addStateState = function(country, data){
country.states.push({'name' : data.newState});
data.newState = "";
};
});
HTML:
<div ng-controller="countryController">
{{name}}
<ul>
<li ng-repeat="country in countries">
{{ country.name }}
<ul ng-show="country.states.length > 0">
<li ng-repeat="state in country.states">
{{ state.name }}
</li>
</ul>
<input type="text" ng-model="data.newState" />
Add
{{data.newState}}
</li>
</ul>
</div>
When you are dealing with things like ng-repeat, ng-if, or ng-include, they each create a new scope. This means that when you try to bind to a primitive on the root level of that scope, it will get dereferences when you update the value. So, you need to put your primitives inside of an object. John Papa's style guide recommends making a "vm" property on your scope. vm stands for view model.
Here is a jsfiddle of how to use it.
http://jsfiddle.net/fbLycnpg/
vm.newState

ng-repeat doesn't auto refresh after save

I am trying to post some data via save but cannot see the data in the browser unless i refresh, the todo.id is showing straight away but not the todo.name
<body ng-controller="TodoCtrl">
<div ng-repeat="todo in Todos.record">
<div>{{todo.id}} : {{todo.name }}</div>
</div>
<div>
<input ng-model="todo.name" />
<button ng-click="addItem()">Add Item</button>
</div>
</body>
var app = angular.module("myApp",['ngResource']);
app.factory("Todo",function($resource){
return $resource(
"http://localhost/rest/motors/users?app_name=motors",
{},
{
query: {method: 'GET',isArray: true},
get: {method: 'GET'},
save:{method:'POST'}
}
)
})
app.controller("TodoCtrl", function ($scope, Todo) {
"use strict";
$scope.Todos = Todo.get();
$scope.addItem = function(){
Todo.save($scope.todo, function(data){
$scope.Todos.record.push(data);
$scope.todo={};
});
}
})
If that code sample is representative of your real code, it's likely a problem that the "input" field that references "todo.name" is OUTSIDE of the ng-repeat loop, so that is defining a model property outside of your "Todos.record" list.
adding &fields=* in the api url solved the issue. eg changed
"http://myexample.com/rest/motors/users?app_name=motors"
to
"http://myexample.com/rest/motors/users?app_name=motors&fields=*"
Thanks for help.

Display nested JSON items in AngularJS

SOLVED:
This is my first effort to try out REST with AngularJS to display the location of the user and some required data (nested items) from the JSON data.
I am hitting this URL: http://muslimsalat.com/daily.json?callback=JSON_CALLBACK
I need to show the below data in a list way which is a nested item:
"items":[
{
"date_for": "2014-5-5",
"fajr": "4: 10am",
"shurooq": "5: 36am",
"dhuhr": "12: 15pm",
"asr": "3: 43pm",
"maghrib": "6: 55pm",
"isha": "8: 25pm"
}]
and also the below information to show the location.
{
"city": "XX",
"country": "XX",
}
AngularJS:
var App = angular.module('MyRESTApp',[]);
App.controller("myRestCntrl",function ($scope, $http) {
var locationURL = "http://muslimsalat.com/daily.json" + "?callback=JSON_CALLBACK";
$http.jsonp(locationURL).
success(function(data)
{
$scope.myLocation = data;
});
});
HTML:
<div ng-app="MyRESTApp">
<div ng-controller="myRestCntrl">
//ng-repeat here for items
<ul>
<li>Date:{{}}</li>
<li>Fajr:{{}}</li>
//more li
</ul>
</div>
</div>
Please let me know how can I loop through nested items and location for the above JSON URL.
You're looking for ng-repeat. Please read and follow the examples on:
https://docs.angularjs.org/api/ng/directive/ngRepeat
If you're still having trouble, please set up a plunker so we'll see what's wrong.
Solved:
<div class="container" ng-controller="namazTimesCtrl">
<ul ng-repeat="item in myLocation.items">
<li>
Date - {{item.date_for}}
</li>
<li>
Fajr - {{item.fajr}}
</li>
</ul>
</div>

Resources