How to parse a simple array with ng-admin - angularjs

I have an API (http://localhost:5000/v2/_catalog) returning a json structure as follows:
{
"repositories":
[
"start/imageA",
"start/imageA"
]
}
Now I want to parse the result with ng-admin. My admin.js (CORS is solved on my webserver) looks as follows:
var myApp = angular.module('r2ui', ['ng-admin']);
myApp.config(['RestangularProvider', function(RestangularProvider) {
RestangularProvider.addFullRequestInterceptor(function(element, operation, what, url, headers, params, httpConfig) {
delete params._page;
delete params._perPage;
delete params._sortDir;
delete params._sortField;
return { params: params };
});
}]);
myApp.config(['NgAdminConfigurationProvider', function (nga) {
var admin = nga.application('Registry v2 UI')
.baseApiUrl('http://localhost:8081/v2/'); // main API endpoint
var catalog = nga.entity('_catalog');
catalog.listView().fields([
nga.field('repositories', 'embedded_list')
.targetEntity(nga.entity('repositories'))
.targetFields([
nga.field('.').isDetailLink(true),
nga.field('.').label('Repository')
])
.listActions(['edit'])
]);
admin.addEntity(catalog);
nga.configure(admin);
}]);
How can this be achieved?
Update below
Sorry I omitted the file index.html cause I thought it is to obvious to mention:
<head>
<meta charset="utf-8">
<title>Registry v2 UI</title>
<link rel="stylesheet" href="node_modules/ng-admin/build/ng-admin.min.css">
</head>
<body ng-app="r2ui">
<div ui-view></div>
<script src="node_modules/ng-admin/build/ng-admin.min.js" type="text/javascript"></script>
<script src="admin.js" type="text/javascript"></script>
</body>
</html>
The question is still the same. The array is not parsed correctly and I do not find in the documentation how this could be achieved with the given json.

I've got the same problem, and I finally solved it by set the field type to "choices".
In your case, try to change:
nga.field('repositories', 'embedded_list')
to:
nga.field('repositories', 'choices')

Related

Unable to send data from controller to component

I have situation where I would like to configure component in html code. I have the following structure.
game.html which is served as in url like example.com/game/7999 which should show page for game 7999.
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<base href="/">
<title>Providence</title>
<script src="/js/angular.js"></script>
<script src="/data-access/data-access.module.js"></script>
<script src="/data-access/data-access.service.js"></script>
<script src="/score-info/score-info.module.js"></script>
<script src="/score-info/score-info.component.js"></script>
<script src="/js/game.js"></script>
</head>
<body>
<div ng-controller="myController">
<p> {{ game_id }} </p>
<score-info game_id="{{ game_id }}"></score-info>
</div>
</body>
Corresponding game.js, which seem to work as game_id shows up correctly.
angular.module('myApp', [
'dataAccess',
'scoreInfo' ],
function($locationProvider){
$locationProvider.html5Mode(true);
});
angular.
module('myApp').
controller('myController', function($scope, $location) {
var split_res = $location.path().split('/');
var game_id = split_res[split_res.length-1];
$scope.game_id = game_id
});
My problem lies in component where I'm unable to inject the game_id. Here's score-info.component.js where the game_id does not become visible.
angular.
module('scoreInfo').
component('scoreInfo', {
templateUrl : '/score-info/score-info.template.html',
controller : function ScoreInfoController(dataAccess) {
self = this;
console.log(self.game_id) // self.game_id == undefined
dataAccess.game(self.game_id).then(function(game) {
self.game = game;
});
},
bindings : {
game_id : '<'
}
});
I noticed that some earlier answers recommended using a separate service of wiring up controller and component. That does not work for me as I need to be able to include varying number of scoreInfo -blocks in a single page.
I'm going to answer this myself. The answer was provided by JB Nizet in comments.
First problem was naming related. The code needs to stick with angular.js' naming convention and use gameId: '<' and use <score-info game-id="game_id">
Also < binding must have the reference in the element without curly braces: <score-info game-id="game_id">
Finally, the components controller needs to take in to the account breaking changes between angular 1.5 -branch and 1.6 -branch. See angular CHANGELOG. Specifically ScoreInfoController becomes
function ScoreInfoController(dataAccess) {
self = this;
self.$onInit = function() {
dataAccess.game(self.game_id).then(function(game) {
self.game = game;
})
}

Mapping curl statement to $http.post

I am a beginner in angular js. I am experimenting with $http service in angularjs. I am accessing a web service. It returns expected response when using curl statement in ubuntu but is not succeeding when the parameter in curl is mapped to $http.post() parameter. Please take a look at my code for both curl and angularjs page. Please point me out my mistake and help me to resolve the issue.
curl --data "email=test#test5.com" HTTP://dummy.dummyplane.com/dummyservices/UserExists
Result:
{"Data":"123456","Success":true,"Exception":null}
Angularjs code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="registerController">
<button ng-click='Register()' style='margin-top:15px'>Register</button>
</div>
<script type="text/javascript">
var app = angular.module('myapp', []);
app.controller('registerController', function($scope, $http) {
$scope.Register = function() {
$http({
url:'http://tethys.dev.riekerinc.com/totalsolutions/UserExists/',
method:'POST',
data:{"email":"tina#test5.com"},
headers:{'Content-Type':'application/x-www-form-urlencoded'}
}).success(function(data){
//console.log(data)
alert("Success");
});
};
});
</script>
</body>
</html>
You set the content type to the correct value, but you don't tell angular to use a different serializer than the default one, so it still sends it in JSON format.
Use $httpParamSerializerJQLike, or simply send the data as a string:
data: 'email=tina#test5.com'

Displaying a WordPress JSONP blog post title in angular-ui ui-calendar

I'm new to angular, so apologies if this has an obvious answer. I want to display a blog post title and its published date, as the start date, on the ui-calendar. It works fine with hardcoded start, end and title values but nothing is returned when in the success directive when I make a jsonp call.
The jsonp call works fine if I don't use the calendar, so I think it's a syntax issue.
This is my angular code (with hard-coded dates):
var MyController = function($scope) {
$scope.uiConfig = {
...
};
$scope.eventSources = [$scope.events];
$scope.events = [
{
start : '2015-04-20',
end : '2015-04-21',
type: "GET",
url: 'http://calendar.jacarandatech.com/wp-json/posts/5/?_jsonp=?',
dataType: 'jsonp',
success: function(response) {
//what do I put here to display the response.title??
}
}
]
};
angular
.module('MyApp', ['ui'])
.controller('MyController', MyController);
and my html code:
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<link rel="stylesheet" href="bower_components/fullcalendar/fullcalendar.css"/>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script src="http://code.angularjs.org/1.0.1/angular-1.0.1.js" ng:autobind></script>
<script type="text/javascript" src="bower_components/angular-resource/angular-resource.js"></script>
<script src="http://www.dillingermediaonline.com/angular-ui.js"></script>
<script type="text/javascript" src="bower_components/jquery-ui/ui/jquery-ui.js"></script>
<script type="text/javascript" src="bower_components/angular-ui-calendar/src/calendar.js"></script>
<script type="text/javascript" src="bower_components/fullcalendar/fullcalendar.js"></script>
<script type="text/javascript" src="bower_components/fullcalendar/gcal.js"></script>
<script type="text/javascript" src="app.js"></script>
<title>ng calendar</title>
</head>
<body>
<div ng-controller="MyController" calendar="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources"></div>
</body>
</html>
jsonp code (works fine):
$.ajax({
type: "GET",
url: 'http://calendar.jacarandatech.com/wp-json/posts/5/?_jsonp=?',
dataType: 'jsonp',
success: function (response) {
var posttitle = response.title;
var timestamp = response.modified_gmt;
console.log('post title = ' + posttitle);
console.log('timestamp = ' + timestamp);
}
});
I researched the following stackoverflow questions but couldn't get their solutions to work:
How do I use jsonp with angular-ui calendar
Angular JSONP calling WordPress JSON REST API
You need to make sure that the variables that contain the title and the timestamp are within the controller's scope.
First, in the first line add $http in the controller like this:
var MyController = function($scope, $http) {
then declare the variables:
$scope.postTitle = '';
$scope.postTimestamp = '';
You should use $http to make the AJAX call. The other function you showed is not needed.
$http.get('http://calendar.jacarandatech.com/wp-json/posts/5/?_jsonp=?').success(function (res) {
$scope.postTitle = res.title;
$scope.postTimestamp = res.modified_gmt;
});
This will let you declare the calendar event like this:
start : $scope.postTimestamp,
title : $scope.postTitle

including external js file into angular

I have a java script file that contains a config object for decoding a lot of business jargon for ease of use in my application.
How can I get that to be available to my angular app? I currently have it included in my html file above all the application files.
here is my config.js:
var config = {
"metadata":[
"8235205241531AF399B113140005492E":{
"name":"verison_number"
}
]
}
here is includes:
<script src="libs/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-resources/angular-resource.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<script src="js/config.js"></script>
<script src="js/viewer.js"></script>
<script src="js/controller.js"></script>
<script src="js/services.js"></script>
<script src="js/routes.js"></script>
<script src="js/app.js"></script>
now here is my controller just trying to do a console.log on it:
var MainCtrl = angular.module('MainCtrl', []);
MainCtrl.controller('loader',['$scope','$rootScope','$http','startApp', function($scope,$rootScope,$http,startApp) {
console.log(config);
console.log('loading course...');
console.log(startApp);
}]);
Your JSON is incorrect.
Here is the correct way for declaring config:
var config = {
"metadata":[
{"8235205241531AF399B113140005492E":"verison_number"}
]}
Working Plunkr
Maybe using the value recipe. For example:
var app = angular.module('MainCtrl');
// later
app.value('myconfigs',config); // set your "object"
// somewhere in your controller code
MainCtrl.controller('loader',['$scope','$rootScope','$http','startApp','myconfigs', function($scope,$rootScope,$http,startApp, myconfig) {
console.log(myconfig.metadata);
console.log('loading course...');
console.log(startApp);
}]);

AngularJS. $resource, MongoLab, Restful API - What's wrong with my sample?

I am new to AngularJS and loving it as I learn it. I am trying to figure out how to communicate with MongoLab from AngularJS using $resource and RESTful API. I have the following two files:
index.html:
-----------
<!DOCTYPE html>
<html lang="en">
<head>
<title>MongoLab Connectivity Test</title>
<script src="angular.js"></script>
<script src="angular-resource.js"></script>
<script src="app3.js"></script>
<link rel="stylesheet" href="bootstrap.css" />
<link rel="stylesheet" href="bootstrap-theme.css" />
</head>
<body ng-app="myModule">
<div ng-controller="display">
<p>{{data.message}}</p>
</div>
</body>
</html>
app3.js:
--------
var myModule = angular.module('myModule', ['ngResource']);
myModule.controller('display', function($scope, personService) {
$scope.data = personService.query();
});
myModule.constant({
DB_BASEURL: "https://api.mongolab.com/api/1/databases/db1/collections",
API_KEY: "<MyAPIKey>"
})
myModule.factory('personService', ['$resource', 'DB_BASEURL', 'API_KEY',
function($resource, DB_BASEURL, API_KEY)
{
return $resource
(DB_BASEURL+'/persons/:id'
,{id: "#id" apiKey: API_KEY}
);
}
]);
When I try it, I get the following output:
{{data.message}}
I am not sure what I am doing wrong. Hoping to get some help.
A better way to connect would be : https://github.com/pkozlowski-opensource/angularjs-mongolab
[copying the text from documentation AS IT IS]
Usage instructions
Firstly you need to include both AngularJS and the angular-mongolab.js script : https://raw.githubusercontent.com/pkozlowski-opensource/angularjs-mongolab/master/src/angular-mongolab.js
Then, you need to configure 2 parameters:
MongoLab key (API_KEY)
database name (DB_NAME)
Configuration parameters needs to be specified in a constant MONGOLAB_CONFIG on an application's module:
var app = angular.module('app', ['mongolabResourceHttp']);
app.constant('MONGOLAB_CONFIG',{API_KEY:'your key goes here', DB_NAME:'angularjs'});
Then, creating new resources is very, very easy and boils down to calling $mongolabResource with a MongoDB collection name:
app.factory('Project', function ($mongolabResourceHttp) {
return $mongolabResourceHttp('projects');
});
As soon as the above is done you are ready to inject and use a freshly created resource in your services and controllers:
app.controller('AppController', function ($scope, Project) {
Project.all().then(function(projects){
$scope.projects = projects;
});
});
Also, you may check out the blog here for even simpler implementation : http://asad.io/angularjs-with-mongolab/
Use the $http module by Angular and Mongolab REST API
For GET request,
$http.get('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY')
.success(function(data) {
console.log(data)
}
For POST request,
$http.post('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY', $scope.data, {
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
})
.success(function() {
console.log('Data saved successfully')
}
More on http method support documentation - http://docs.mongolab.com/data-api/#reference

Resources