Angular.js working with a single element in a JSON Document - json

I have some JSON e.g.
[{
'name': 'test',
'phone': '012345678',
'date': '02/03/2014'
},
{ ... }
]
A controller something like :
var app = angular.module('App', []);
app.controller('NameListCtrl', function($scope, $http) {
$http.get('/api/v1/names.json').success(function(names) {
$scope.names = names;
});
});
HTML/JADE something like :
div#names(ng-controller="NameListCtrl")
li.course_list(ng-repeat="name in names | orderBy:'date1'")
span
{{name.date}}) // I want to do some formatting on this
span
{{name.name}}
I would like to perform a formatting operation on each date, is there a way of doing so without using filters ? I have seen something using the $httpProvider.

A way to do it in the controller... insert your own filter func.
app.controller('NameListCtrl', function($scope, $http, $filter) {
$http.get('/api/v1/names.json').success(function(names) {
angular.forEach(names, function(item){
item.date = $filter('date')(item.date, "shortDate");
});
$scope.names = names;
});
});
You could also use jade and do:
{{name.date|date:'shortDate'}})

Related

AngularJS: Is it possible for the following URL to be used in a form?

In a form for an AngularJS page, is it possible to use the following URL to be set for a method?
https://example.com/transaction-address/id3
I've tried doing this, but the email id I've set is not being passed. The form is being handled in the injected script and the problem (or maybe a mistake) is in the line that injects the 'id3' method.
In the script for the ng-app, I've set the 'id3' method:
angular.module('app', [])
.factory('Account', function($q, $u, $sce) {
$q.all([
['$http',
{'id1': 1,
'id2': 2,
'id3': 3,
'id4': 4,}
]).then(function (response) {
var sl = 'id3';
$sce.trustAsResource('id3', sl);
response.end();
});
});
You don’t need to automatize the id3 string here. Just assign it to a variable:
angular.module('app', [])
.factory('Account', function($q, $u, $sce) {
$q.all([
['$http',
{'id1': 1,
'id2': 2,
'id3': 3,
'id4': 4,}
]).then(function (response) {
var sl = 'id3';
response.sendValue(sl);
})
});

Angular load local json and get arrays

I am new in angular and I am trying to load json file and repeat it on index file but can get through that json to get the arrays for repeat
app.js
chatApp.controller('userCtrl', function ($scope, $filter, $http) {
var obj = {content:null};
$http.get('test.json').success(function(data) {
obj.content = data;
});
console.log(obj);});
json file
{"data":
{"result":"success","customers_list":[
{"Chat":
{
"name": "John",
"town":"LA"
}},
{"Chat":
{
"name": "Peter",
"town":"NY"
}}],"message":"The function is correctly"}}
I would like to get the name and town , any ideas how to go through data-> customer_list untill I get something like:
$scope.loadChat =[
{
"name": "John",
"town":"LA"
},
{
"name": "Peter",
"town":"NY"
}
];
You can use the built in map function:
chatApp.controller('userCtrl', function ($scope, $filter, $http) {
$scope.loadChat = [];
$http.get('test.json').success(function(data) {
$scope.loadChat = data.data.customers_list.map(function(chat) {
return chat.Chat;
});
});
});
The map() method creates a new array with the results of calling a
provided function on every element in this array.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
tYou can display the name and town looping trough content.data.customers_list with ng-repeat.
controller:
chatApp.controller('userCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('test.json').success(function(data) {
$scope.content = data;
});
}]);
html:
<div ng-repeat="user in content.data.customers_list">
{{user.Chat.name}} {{user.Chat.town}}
</div>

Displaying nested JSON with angularjs

I am trying to display nested JSON in a page. I'm not sure how to drill down into it.
In my app js file I have an parameter called initialData that I want to call a function getProducts() when the view is called...
'use strict';
var quoteApp = angular.module('quoteApp', ['ui.router']);
quoteApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
templateUrl: 'ng-views/choose.html',
controller: "quoteBuilderController",
resolve: {
initialData: ['quoteApi', function (quoteApi) {
return quoteApi.getProducts();
}]
}
})
});
my quoteApi looks like this in case you want to see it...
(function () {
'use strict';
angular.module('quoteApp').factory('quoteApi', quoteApi);
quoteApi.$inject = ['$http'];
function quoteApi($http) {
var service = {
getProducts: getProducts,
getPrices: getPrices
};
var baseUrl = 'http://www.website.com/api/Pricing';
return service;
function getProducts() {
return httpGet('/GetProductCatalogue');
}
function getPrices() {
return httpGet('/GetPrices');
}
/** Private Methods **/
function httpExecute(requestUrl, method, data){
return $http({
url: baseUrl + requestUrl,
method: method,
data: data,
headers: requestConfig.headers }).then(function(response){
return response.data;
});
}
function httpGet(url){
return httpExecute(url, 'GET');
}
}
})();
So quoteApi.getProducts() returns JSON that looks like this...
{
"Cat1": [
{
"product_id": 1,
"product_name": "Prod1"
},
{
"product_id": 2,
"product_name": "Prod2"
}
],
"Cat2": [
{
...
}
]
}
My controller for the view looks like this...
(function () {
'use strict';
angular.module('quoteApp').controller('quoteController', ['$scope', '$http', '$timeout', quoteController]);
quoteController.$inject = ['initialData', 'quoteApi'];
function quoteController($scope, initialData) {
$scope.cat1Products = initialData;
};
})();
So my question is, how can I get 'initialData' to load products from Cat1 only? Should I try to do this from the html? It seems like it should be straight forward enough but I can seem to get it. Thank you.
You need to transform your response from your http request further so you only return the piece you require, and you may also want to consider using the .then() approach:
$http.get('/someUrl').then(function(response) {
//Do something with response.data.Cat1 here
}, function(errResponse) {
console.error('Error while fetching data');
});
Just take out cat1 from your initialData object
function quoteController($scope, initialData) {
$scope.cat1Products = initialData['Cat1'];
};

Angular using $routParams to filter json data retrived

I'd like to filter the JSON being displayed by the route param provided. I have a list page which displays all of the json data and a detail page which I would like to just display the json matching the id in the routeparam.
This is my service:
app.factory("HC", ["$resource", function($resource) {
return {
API: $resource('/api/hc')
}
}]);
This is my controller which is working for displaying all of the results. How could I filter these by the requestParams?
app.controller('servicesDetail', ['$scope', 'HC', '$resource', '$routeParams', function ($scope, HC, $resource, $routeParams ) {
HC.API.query(function(results) {
$scope.services = results;
});
$scope.services = []
}]);
And here are my routes
.when('/services', {
templateUrl: 'templates/services.html',
controller: 'servicesController'
})
.when('/services/:serviceId', {
templateUrl: 'templates/servicedetail.html',
controller: 'servicesDetail'
})
Your json is not valid but in case it has format like that :
{ "_id" : "53bc36b8b7bbbf77208dec62", "name" : "this is from the client", "__v" : 0 }
you can use filterFilter service please see demo here http://jsbin.com/somob/1/edit?html,js,output
but the best option is send serviceId to server and get a single service from server instead array of services and filter them after
app.controller('servicesDetail', ['$scope', 'HC', '$resource', '$routeParams', 'filterFilter',
function ($scope, HC, $resource, $routeParams, filterFilter) {
$scope.services = [];
HC.API.query(function (results) {
$scope.services = results;
});
$scope.serviceId = $routeParams.serviceId;
$scope.serviceById = filterFilter($scope.services, {
_id: $routeParams.serviceId
});
}]);
html:
<!--just for testing -->
<p>ServiceId : {{serviceId }}</p>
<pre>{{serviceById |json}}</pre>

Accessing model data from a view with backbone.js

I have the following code but am struggling to get my view to render the template instead of my model. It all works fine if I render the handlebars template through my model but would like to separate my code into the view.
var DataModel = Backbone.Model.extend({
initialize: function () {
$.getJSON('js/data.json',function(data){
$('.one-wrapper').append(Handlebars.compile($('#one-template').html())(data));
$('.one-asset-loader').fadeOut('slow');
});
},
defaults : function () {
},
});
var StructureView = Backbone.View.extend ({
initialize: function () {
}
});
var structureView = new StructureView({model: new DataModel()});
You can access the model inside the view using this.model.
Your code should look something like:
var StructureView = Backbone.View.extend ({
initialize: function () {
_.bindAll(this);
this.render();
this.model.on('change',this.render);
},
render: function() {
$('.one-wrapper').empty().append(Handlebars.compile($('#one-template').html())( this.model.toJSON() ));
}
});
This will work assuming your model actually contains the data. To do this you need to use the model.url and model.fetch() (not $.getJSON)