ajax call and $.watch in Angular - json

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>

Related

Printing Ajax results in HTML

I have this J Query code:
$(document).ready(function(){
var $outData = $('#data');
var ajaxUrl = 'url.json';
$.ajax(
{
type: 'GET',
url:ajaxUrl,
success: function (result) {
console.log(result.passwords);
}
})
}
);
JSON file looks like this:
{
"passwords":[
{
"value":"tom",
"count":"432517"
},
{
"value":"anaconda",
"count":"454658"
},
{
"value":"111111",
"count":"148079"
},
What I need to do, is to print out each of these objects to be printed out in an ordered list (for instance it should look like this:
tom 432517
anaconda 454658
111111 148079
So far, nothing I have tried works. Althoug, I can console.log the entire object. Any suggestions?
Example rendering:
var $outData = $('#data');
var ajaxUrl = 'url.json';
$.ajax(
{
type: 'GET',
url:ajaxUrl,
success: function (result) {
result.passwords.forEach(pwd => $outData.append(`<div>${pwd.value} ${pwd.count}</div>`));
}
})
}
);
you can create elements and append to dom when you are done,
const data = {
"passwords": [{
"value": "tom",
"count": "432517"
},
{
"value": "anaconda",
"count": "454658"
},
{
"value": "111111",
"count": "148079"
}
]
}
const ol = document.createElement("ol");
for (const {
value,
count
} of data.passwords) {
const li = document.createElement("li")
li.innerText = `${value} -> ${count}`
ol.appendChild(li)
}
document.querySelector("#root").appendChild(ol)
<div id="root"></div>

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>

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.

Add Properties after json load

I have this json:
{
"info": [
{
"id": 999,
"products": [
{
"id": 1,
},
{
"id": 2,
}
]
}
]
}
Info
-- products
-----id
And my factory:
AppAngular.factory('model', ['$http', function ($http) {
return {
load: function (scope) {
$http.get('mydomain/api').success(function (data) {
var myObject = {};
angular.extend(myObject,data);
for (var i = 0; i < myObject.info.length; i++) {
for (var j = 0; j < myObject.info[i].products.length; j++) {
myObject.info[i].products[j].selected = true;
myObject.info[i].products[j].quantity = 1;
.....
}
}
}
});
}
};
} ]);
Theres is a way do add some property after angular.extend, without using a lot of for? We need do add some properties or behavior to the object after make json get.
For exemple:
Info
-- products
-----id
-----selected
-----quantity
You could use angular.forEach:
AppAngular.factory('model', ['$http', function ($http) {
return {
load: function (scope) {
$http.get('mydomain/api').success(function (data) {
var myObject = {};
angular.extend(myObject,data);
angular.forEach(myObject.info, function (info) {
angular.forEach(info.products, function (product) {
product.selected = true;
product.quantity = 1;
.....
});
});
});
}
};
}]);

BackboneJS - this.collection is undefined

i have this Backbone View:
define(['backbone','handlebars', 'text!templates/AlphabetList.html'],
function(Backbone,Handlebars, Template) {
'use strict';
var View = Backbone.View.extend({
template: Handlebars.compile(Template),
events: {
'click li':'li_clickHandler'
},
li_clickHandler: function(e) {
var id = $(e.currentTarget).attr('data-id');
Backbone.history.navigate('/category/'+id, {trigger:true});
},
initialize: function () {
},
render: function() {
$(this.el).html(this.template({menu:this.collection.toJSON()}));
return this;
}
});
return View;
}
);
here is my router:
define([
'backbone',
//Views
'views/ArtistTopImage',
'views/AlphabetList',
'collections/AlphabetCollection',
],
function(
Backbone,
AlphabetList,
ArtistTopImage,
AlphabetCollection
) {
'use strict';
var ArtistRouter = Backbone.Router.extend({
routes: {
'': 'index'
},
//Initializing the application
initialize: function () {
var self = this;
//Collections
this.AlphabetCollection = new AlphabetCollection({catId:0});
//Views
this.artistTopImageView = new ArtistTopImage({el:'.ti'});
this.AlphabetList = new AlphabetList({el:'#alphabetical', collection:this.AlphabetCollection});
self.artistTopImageView.render();
this.AlphabetCollection.fetch({success: function(collection) {
self.AlphabetList.collection=collection;
self.AlphabetList.render();
}});
Backbone.history.start({
pushState: false
});
},
//Default route.
index: function () {
var self = this;
},
});
return ArtistRouter;
}
);
And here is my Collection:
define([
"backbone",
"models/AlphabetModel"
],
function(Backbone, AlphabetModel) {
var AlphabetCollection = Backbone.Collection.extend({
model: AlphabetModel,
catId: null,
initialize: function(attrs) {
this.catId=attrs.catId;
},
url: function() {
return "Alphabetical"+this.catId+".json";
}
});
return AlphabetCollection;
});
The HTML template
<ol class="alist">
{{#each menu}}
<li data-id="{{this.url}}">{{this.name}}</li>
{{/each}}
</ol>
and the JSON file:
[
{
"name":"0-9",
"id":"1",
"url":"0"
},
{
"name":"A",
"id":"2",
"url":"1"
},
{
"name":"B",
"id":"3",
"url":"2"
},
{
"name":"C",
"id":"4",
"url":"3"
},
{
"name":"D",
"id":"5",
"url":"4"
}
]
this gives me an error: "this.collection is undefined". I dont know what the problem is, so does someone have an idea?