How to validate JSON data with ng-pattern - html

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>

Related

Chart.JS Underfined with JSON

Hello guys i got a problem, i cant display my graph it will become like this
As u can see there i also print console log.Nothing error occur.
Below is my index.php
<!DOCTYPE html>
<html>
<head>
<title>Line</title>
</head>
<body>
<div class="chart-container">
<canvas id="line-chartcanvas"></canvas>
</div>
<script src="js/Chart.bundle.min.js"></script>
<script src="js/jquery.js"></script>
<script src="js/chartmain.js"></script>
</body>
</html>
My chartmain.js
$(function(){
$.ajax({
url:"http://localhost/Media/chart.php",
type: "GET",
success : function (data) {
var count = [];
var displayLink = [];
for(var i in data){
count.push ("Player" + data[i].count);
displayLink.push(data[i].displayLink);
}
var chartdata = {
labels: displayLink,
datasets : [
{
data: displayLink,
label : 'Score',
backgroundColor:
"#F1c40F"
}
]
};
var ctx =$("#line-chartcanvas");
var barGraph = new Chart(ctx,{
type: 'bar',
data: chartdata
});
console.log(data);
},
error : function (data) {
console.log(data);
},
});
});
My Json Array
[
{
"count": "3",
"displayLink": "www.bharian.com.my"
},
{
"count": "1",
"displayLink": "www.hmetro.com.my"
},
{
"count": "6",
"displayLink": "www.nst.com.my"
},
{
"count": "1",
"displayLink": "www.sinarharian.com.my"
},
{
"count": "1",
"displayLink": "www.utusan.com.my"
}
]
I think perhaps it cant read my data from JSON but in console log it read
Thanks for helping me, already found the answer, I cant get data from JSON but i can data from MySQL

ajax call and $.watch in Angular

I need to generate a select menu when a button is clicked. I am making an ajax call to get json data from external file, upon button click. which In turn should update the select with data from json. with the code below the select gets updated only after the button is clicked twice. I am watching the jsonData but its not working as expected.
HTML:
<div ng-controller="MainViewCtrl">
<button ng-click="getDeployedResources()"> Load Resources </button>
<select ng-model="selectedOption.name" ng-options="item.name as item.name for item in jsonData"></select>
</div>
json from dropdown.json:
{
"DeployedResources": {
"-env": "dev13",
"ResourceList": {
"-exportTime": 1444999007878,
"Resource": [{
"name": "default",
"type": "project"
},
{
"name": "System",
"type": "project"
},
{
"name": "StratusCommonServices",
"type": "project"
}]
}
}
}
JS:
var app = angular.module('JSONedit', ['ui.sortable'])
.controller('MainViewCtrl', ['$scope', '$http', '$filter','$compile', function ($scope, $http, $filter, $compile) {
$scope.jsonData = {};
$scope.getDeployedResources = function () {
$.ajax({
url: 'json/dropdown.json',
dataType: 'json'
}).done(function (data) {
$scope.jsonData = data.DeployedResources.ResourceList.Resource;
$scope.selectedOption = angular.copy($scope.jsonData[0]);
});
}
$scope.$watch('jsonData', function (json) {
$scope.jsonString = $filter('json')(json);
}, true);
$scope.$watch('jsonString', function (json) {
try {
$scope.jsonData = JSON.parse(json);
$scope.wellFormed = true;
} catch (e) {
$scope.wellFormed = false;
}
}, true);
}])
This is the correct life-cycle of a simple AngularJS Component!
Don't use jQuery for doing something that angular does better!
angular
.module('test', [])
.service('DataService', function($q, $http) {
var self = this;
var mock = {
id: 1,
"DeployedResources": {
"-env": "dev13",
"ResourceList": {
"-exportTime": 1444999007878,
"Resource": [{
"name": "default",
"type": "project"
}, {
"name": "System",
"type": "project"
}, {
"name": "StratusCommonServices",
"type": "project"
}]
}
}
};
self.load = function() {
console.log('loading data', mock.id);
for (var i = 0, len = mock.DeployedResources.ResourceList.Resource.length; i < len; i++) {
mock.DeployedResources.ResourceList.Resource[i].name += mock.id;
}
mock.id += 1;
return $q.when(mock);
return $http
.get('/api/data/')
.then(function(result) {
return result.data;
});
}
})
.controller('TestCtrl', function($scope, DataService) {
var vm = $scope;
vm.select = {
current: null,
items: []
};
vm.loadData = function(event) {
console.count('load data');
return DataService
.load()
.then(function(data) {
vm.current = data.id;
return data.DeployedResources.ResourceList.Resource;
})
.then(function(items) {
vm.select.items = items;
vm.select.current = vm.select.items[0];
})
};
vm.loadData();
});
.select-wrapper {
padding: 1em 2em;
background: yellow;
}
.select-wrapper select {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<article ng-app="test">
<div ng-controller="TestCtrl">
<button type="button" ng-click="loadData($event);">LoadNew</button>
<div class="select-wrapper">
<select ng-model="select.current" ng-options="item as item.name for item in select.items"></select>
</div>
<div ng-bind="select.items | json"></div>
</div>
</article>

ReactJS - Error while loading data from json file

<html>
<head>
<meta charset="utf-8">
<title>React component</title>
<script src="build/react.js"></script>
<script src="build/JSXTransformer.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="myContent"></div>
<script type="text/jsx">
var ChatMessagesLists = React.createClass({
getInitialState: function() {
return {data: {chat_messages:[]}};
},
render: function(){
return
(
<div className="chatLstsWrapper">
<h1>Chat Messages</h1>
<ChatMessagesData data={this.state.data} />
</div>
)
},
componentDidMount: function(){
$.ajax({
url: 'jsontextfile.json',
dataType: 'json',
success: function(data){
this.setState({data: {chat_messages:[]}});
}
});
}
});
var ChatMessagesData = React.createClass({
render:function(){
console.log(this.props.data.chat_messages);
return(
<ul className="chatLsts">
{
this.props.data.chat_messages.map(function(chatmessages){
return <li>{chatmessages.from_account_id}</li>
})
}
</ul>
)
}
})
React.render(<ChatMessagesLists />,document.getElementById("myContent"));
</script>
</body>
</html>
JSON File
{
"message": "List of chat messages",
"data": {
"since_index": 1,
"before_index": 2,
"chat_messages": [
{
"text": "Load more",
"type": "text",
"key": "8ff134e7-e302-445b-903e-0038097c8a29"
},
{
"text": "my test data",
"type": "text",
"key": "3c7c3065-3701-4350-a64a-8a52f9fe1578"
},
{
"text": "My message",
"type": "text",
"key": "40f7c342-a019-44c3-ad2b-8b2ae018972b"
}
],
"max_results": 20
},
}
While loading the data getting below error. Can anyone please suggest where am i wrong
Error: Invariant Violation: ChatMessagesLists.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.
Hy,
Have you tried:
var ChatMessagesData = React.createClass({
render:function(){
var items = this.props.data.chat_messages.map(function(chatmessages){
return <li>{chatmessages.from_account_id}</li>;
})
return(
<ul className="chatLsts">
{
items
}
</ul>
);
});
PS: In Ajax callback, you not update the state:
success: function(data){
this.setState({data: {chat_messages: data}});
}

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>

how to populate a drop down menu with data coming to controller using http get in angular js

This is the JSON file ..
Using angular js controller and view how can I parse this json and display the drop1 and drop2 values of respective technology in drop down menu.getting the JSON data using http get.
Thanks in advance
{
"technology": [
{
"id": "AKC",
"detail": {
"drop1": [
{
"id": "AKC-lst-1231"
},
{
"id": "AKC-lst-1232"
},
{
"id": "AKC-lst-1233"
}
],
"drop2": [
{
"id": "T_AKC_live"
},
{
"id": "T_AKC_Capt"
},
{
"id": "T_AKC_live1"
}
]
}
},
{
"id": "MET",
"detail": {
"drop1": [
{
"id": "MET-2st"
},
{
"id": "MET-34"
}
],
"drop2": [
{
"id": "sd-232"
},
{
"id": "sd-121"
}
]
}
}
]
}
Please consider this example:
<!DOCTYPE html>
<html ng-app="postExample">
<head>
<script data-require="angular.js#1.2.22" data-semver="1.2.22" src="https://code.angularjs.org/1.2.22/angular.js"></script>
<script src="usersController.js"></script>
<script src="userRepoService.js"></script>
</head>
<body ng-controller="UsersController">
<h1>Post Angular Example</h1>
<select id="UserSelector" style="width: 100%;">
<option ng-repeat="user in users" value="{{user.id}}">{{user.login}} </option>
</select>
</body>
</html>
userRepoService.js
(function(){
var userRepoService = function($http){
var getUsers = function(username){
return $http.get("https://api.github.com/users")
.then(function(response){
return response.data;
});
};
return {
get: getUsers
};
};
var module = angular.module("postExample");
module.factory("userRepoService", userRepoService);
}());
Controller:
(function(){
var app = angular.module("postExample",[]);
var UsersController = function($scope, userRepoService){
var onFetchError = function(message){
$scope.error = "Error Fetching Users. Message:" +message;
};
var onFetchCompleted = function(data){
$scope.users =data;
};
var getUsers = function(){
userRepoService.get().then(onFetchCompleted,onFetchError);
};
getUsers();
};
app.controller("UsersController", UsersController);
}());
You can directly call $http service, and get that response inside success data parameter.
CODE
$http.get("test.json").
success(function(data, status, headers, config) {
//get data and play with it
}).
error(function(data, status, headers, config) {
alert("Error fetching data");
// log error
});
Hope this could help you, Thanks.