ng-repeat data flashes then disappers - html

i have the following .json file:
[
{
"host": "host00",
"avgcpu": "1%",
"maxcpu": "2%",
"freem": "32000"
},
{
"host": "node01",
"avgcpu": "33%",
"maxcpu": "80%",
"freem": "64000"
},
{
"host": "node02",
"avgcpu": "55%",
"maxcpu": "75%",
"freem": "100000"
},
{
"host": "node03",
"avgcpu": "85%",
"maxcpu": "100%",
"freem": "86674"
},
{
"host": "node04",
"avgcpu": "3%",
"maxcpu": "7%",
"freem": "86613"
}
]
I try to read it with the following controller:
angular.module('usagemdl').controller('usagectrl', ['$scope', '$http', function ($scope, $http) {
$http.get('/out/usage.json')
.then(function (response) {
$scope.usages = response.usages;
});
}]);
And then i try to display it with the following html code:
<div class="cards" ng-controller="usagectrl">
<div class="card" style="width: 18rem;" ng-repeat="usage in usages">
<div class="card-header">
{{ usage.host }}
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">{{ usage.avgcpu }}</li>
<li class="list-group-item">{{ usage.maxcpu }}</li>
<li class="list-group-item">{{ usage.freem }}</li>
</ul>
</div>
</div>
ng-app is defined in my <body> which works properly in a different scenario.
Im not sure what im doing wrong.
I can see a empty card for a second but then it dissappers.
Please let me know if you need any further code to find the issue.

I this you should do that one. you are missing data from response.
angular.module('usagemdl').controller('usagectrl', ['$scope', '$http', function ($scope, $http) {
$http.get('/out/usage.json')
.then(function (response) {
$scope.usages = response.data;
console.log($scope.usages);
});
}]);

Related

Parse HTML from a nested JSON file with AngularJS

I am trying to parse nested JSON with AngularJS. There are items in it which will used throughout the page, however there are also nested news items in there. I'm not sure how to work this out.
test.json
{
"CustomerName" : "TEST",
"PaidCustomer" : true,
"LaunchEndDate" : "24-07-2021",
"LauncherTitle" : "Launcher Title",
"LauncherSlogan" : "LauncherSlogan",
"CommunityLogo" : "logo.jpg",
"news" : [
{
"Title" : "News 1",
"Description" : "Newsmessage 1",
"FeaturesImage" : "",
"Author" : "Hutserino",
"Tags" : [ "#launcher", "#HellYeah" ],
},
{
"Title" : "News 2",
"Description" : "news 2",
"FeaturesImage" : "",
"Author" : "Hutserino",
"Tags" : [ "#launcher", "#HellYeah" ]
}
]
}
I've already tried this:
Angular code
<script>
(function() {
angular.module('myApp', []);
function myController($scope, $http) {
return $http.get('launcher.json')
.then(function(response) {
return response.data;
});
return {
LauncherTitle: LauncherTitle,
LauncherSlogan: LauncherSlogan
}
var data = response.data;
data.forEach(data.news, function(clientdata.news, index) {
angular.forEach(clientdata.news, function(newsitem, index){
$scope.news.push(newsitem);
});
});
}
})();
</script>
HTML
<div ng-app="myApp" ng-controller="myController">
<h1 class="display-3">{{ GameLauncherTitle }}</h1>
<h3 class="display-5">{{ GameLauncherSlogan }}</h3>
<div class="card-columns">
<div class="card" ng-repeat="newsitem in news">
<img src="{{ newsitem.FeaturesImage }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title text-dark">{{ newsitem.Title }}</h5>
<p class="card-text text-dark">{{ newsitem.Description }}</p>
</div>
</div>
</div>
</div>
But this isn't returning any results.
You are quitting out of your myController function with the two returns, I think you might have been trying
(function() {
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope, $http) {
$scope.news = []
$http.get('launcher.json')
.then(function(r) {return JSON.parse(r)})
.then(function(response) {
response.news.forEach(function(newsitem){
$scope.news.push(newsitem);
});
});
});
})();
Can you try this instead of your Angular Code?
Cleaned version:
(() => {
const myApp = angular.module('myApp', []);
myApp.controller('myController', ($scope, $http) => {
$scope.news = []
$http.get('launcher.json')
.then(r => JSON.parse(r))
.then(response => {
response.news.forEach(function (newsitem) {
$scope.news.push(newsitem);
})
})
})
})();

Vue won't read JSON response?

If /scheduled_jobs/list returns a JSON object, why is my Vue component not reading it?
Here's the component:
<template>
<div>
<ul v-if="jobs.length">
<li v-for="job in jobs">
{{ job.id }}
{{ job.document_id }}
{{ job.user_id }}
{{ job.schedule }}
{{ job.status }}
</li>
</ul>
<p v-else>
Nothing waiting.
</p>
</div>
</template>
<script>
export default {
data () {
return {
jobs: []
}
},
methods: {
loadData () {
$.get('/scheduled_jobs/list', function (response) {
this.jobs = response.json()
}.bind(this))
},
ready () {
this.loadData()
setInterval(function () {
this.loadData()
}.bind(this), 30000)
}
}
}
</script>
And here's the response from the URL:
{
"id": "8154e79383a950072823410e",
"document_id": 59455,
"user_id": 2,
"schedule": "2018-02-03T12:00",
"status": 2
}
I just get this response:
Nothing waiting.
you are overwriting the array with an object:
methods: {
loadData () {
$.get('/scheduled_jobs/list', function (response) {
this.jobs.push(response.json());
}.bind(this))
}
You're getting an object, not an array, so jobs.length is undefined.

How to validate JSON data with ng-pattern

My app pulls json data and randomises the results on click, how can i validate each result that get's generated and state whether the value is valid/invalid?
view
<div ng-controller="idCtrl">
<button ng-click="randomize()">Random value on click</button>
<p>Id Number: <span data-ng-bind="RandomId.number"></span></p>
<p>Valid?: <span></span> </p>
</div>
json
[
{"number": "8607025402081"},
{"number": "8501016184086"},
{"number": "6104053425672"},
{"number": "8909025012083"},
{"number": "2222222222222"},
{"number": "8888888888888"},
{"number": "0000000000000"},
{"number": "9999999999999"}
]
script
var idApp = angular.module('idApp', []);
idApp.controller('idCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.regex = '(((\d{2}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012]) (0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|([02468][048]|[13579][26])0229))(( |-)(\d{4})( |-)(\d{3})|(\d{7}))';
$scope.randomize = function(){
$http.get('js/idnumbers.json')
.success(function(data) {
$scope.idnumber = data;
var randomIDIndex = Math.floor(Math.random() * $scope.idnumber.length);
$scope.RandomId = $scope.idnumber[randomIDIndex];
console.log(data);
})};
}]);
ngPattern is used with input controls most often. If you wanted to use ngPattern you could do something like the following. However, the invalid values are not being put in the text box. I assume this is because they are...invalid.
Note: I modified your regex from a string to a RegExp.
var idApp = angular.module('idApp', []);
idApp.controller('idCtrl', ['$scope', '$http',
function($scope, $http) {
var data = [{
"number": "8607025402081"
}, {
"number": "8501016184086"
}, {
"number": "6104053425672"
}, {
"number": "8909025012083"
}, {
"number": "2222222222222"
}, {
"number": "8888888888888"
}, {
"number": "0000000000000"
}, {
"number": "9999999999999"
}];
$scope.regex = /(((\d{2}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012]) (0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|([02468][048]|[13579][26])0229))(( |-)(\d{4})( |-)(\d{3})|(\d{7}))/;
$scope.randomize = function() {
//make your HTTP call here
$scope.idnumber = data;
var randomIDIndex = Math.floor(Math.random() * $scope.idnumber.length);
$scope.RandomId = $scope.idnumber[randomIDIndex];
console.log($scope.form.theInput.$valid);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="idApp">
<div ng-controller="idCtrl">
<form name="form">
<button ng-click="randomize()">Random value on click</button>
<p>Id Number: <input name="theInput" ng-pattern="regex" ng-model="RandomId.number"></input></p>
<p>Valid?: <span>{{form.theInput.$valid}}</span> </p>
</form>
</div>
</div>
Since ngPattern is limited to input boxes you may want to just use good ol' JavaScript to accomplish the validation. E.g.,
var idApp = angular.module('idApp', []);
idApp.controller('idCtrl', ['$scope', '$http',
function($scope, $http) {
var data = [{
"number": "8607025402081"
}, {
"number": "8501016184086"
}, {
"number": "6104053425672"
}, {
"number": "8909025012083"
}, {
"number": "2222222222222"
}, {
"number": "8888888888888"
}, {
"number": "0000000000000"
}, {
"number": "9999999999999"
}];
var regex = /(((\d{2}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012]) (0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|([02468][048]|[13579][26])0229))(( |-)(\d{4})( |-)(\d{3})|(\d{7}))/;
$scope.randomize = function() {
//http call here
$scope.idnumber = data;
var randomIDIndex = Math.floor(Math.random() * $scope.idnumber.length);
$scope.RandomId = $scope.idnumber[randomIDIndex];
$scope.valid = regex.test($scope.RandomId.number);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="idApp">
<div ng-controller="idCtrl">
<button ng-click="randomize()">Random value on click</button>
<p>Id Number: <span data-ng-bind="RandomId.number"></span>
</p>
<p>Valid?: {{valid}}
</p>
</div>
</div>

Problems loading Json via $http using angularJS

I have son problems trying to load a Json in a contact App. (based in angular UI)
I'm new on AngularJS and I don't know where is the error (well, yes, the console sayme 'SyntaxError: Unexpected token i')
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.when("", "/contacts/list");
$urlRouterProvider.when("/", "/contacts/list");
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/contacts/list");
$stateProvider
.state('contacts', {
abstract: true,
url: '/contacts',
templateUrl: 'contacts.html',
controller: 'contactController',
onEnter: function(){
console.log("enter contacts");
}
})
.state('contacts.list', {
url: '/list',
// loaded into ui-view of parent's template
templateUrl: 'contacts.list.html',
onEnter: function(){
console.log("enter contacts.list");
}
})
.state('contacts.detail', {
url: '/:id',
// loaded into ui-view of parent's template
templateUrl: 'contacts.detail.html',
controller: function($scope, $stateParams){
$scope.person = $scope.contacts[$stateParams.id];
},
onEnter: function(){
console.log("enter contacts.detail");
}
})
.state('contacts.detail.test', {
url: '/test',
// loaded into ui-view of parent's template
templateUrl: 'contacts.detail.test.html',
onEnter: function(){
console.log("enter contacts.detail.text");
}
});
});
myapp.controller('contactController',function($scope, $http){
$scope.contacts = []; //declare an empty array
$http.get("contacts.json")
.success(function(response){
$scope.contacts = response; //ajax request to fetch data into $scope.data
});
});
Contents of contacts.json:
[{ id:0, name: "Alice" },
{ id:2, name: "Alirce" },
{ id:3, name: "Alwicse" },
{ id:4, name: "Awlice" },
{ id:1, name: "Bob" }]
I made a Plunkr for explain it well
As everyone's saying in the comments, JSON keys must be strings. Replace contacts.json with
[
{ "id":0, "name": "Alice" },
{ "id":2, "name": "Alirce" },
{ "id":3, "name": "Alwicse" },
{ "id":4, "name": "Awlice" },
{ "id":1, "name": "Bob" }
]
Here's a fixed Plunkr

How to select an item from json data with ngResource?

I'm trying to select data from my json file with
$resource request :
Im using a global variable productSelected in my controller,
but when I change it's value with ng-model , that don't do an effect on the model and the value of reference still the same!
Anyone have an idea please ?
Here is my code :
var myApp = angular.module('myApp', ['ngResource']);
myApp.factory('Produits',['$resource', function ($resource) {
return $resource('data/produits.json/:id',{id: "#id"},
{
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
}
);
}]);
myApp.controller('produitsCtrl', function($scope, $http,Produits,$log) {
$scope.productSelected=0;
Produits.query(function(data){
$scope.produits=data;
$scope.reference=$scope.produits[$scope.productSelected].reference ;
});
});
<div ng-app="myApp" >
<div ng-controller="produitsCtrl">
Product : <input type="text" ng-model="productSelected"/> {{ productSelected }} <br/>
Reference : {{reference}}
</div>
</div>
produits.json
[{
"id" : 1,
"reference": "AA"
},
{
"id" : 2,
"reference": "BB"
}]
Just have a look at this code may be helpful for you
<body ng-app="myApp" data-ng-controller="MainCtrl" id="div1">
Product : <input type="text" ng-model="productSelected" ng-change="fun(productSelected)"/> {{ productSelected }} <br/>
Reference :<p ng-model="reference"> {{reference}} </p>
<script>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope){
$scope.productSelected=0;
$scope.produits= [{
"id" : 1,
"reference": "AA"
},
{
"id" : 2,
"reference": "BB"
}];
$scope.reference=$scope.produits[$scope.productSelected].reference;
$scope.fun=function(val){
//alert(val)
if(val!=undefined && val!=null && val!='')
$scope.reference=$scope.produits[$scope.productSelected].reference;
else
$scope.reference=$scope.produits[0].reference;
};
});
</script>
</body>