Need help to make changes in Angular Factory. Have example working with array JSON data, but need this code work with JSON data from $http request, how do that?
This is example Factory:
angular.module('starter.services', [])
.factory('catgs', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var catgs = [{
id: 0,
name: 'CATG1',
items: [{
img:'img/G1I1.png',
name:'category1Item1',
status:'OPEN'
}]
},{
id: 1,
name: 'CATG2',
items: [{
img:'img/G2I1.png',
name:'category2Item1',
status:'OPEN'
},{
img:'img/G2I2.png',
name:'category2Item2',
status:'CLOSED'
}]
}];
return {
all: function() {
return catgs;
},
remove: function(catg) {
catgs.splice(catgs.indexOf(catg), 1);
},
get: function(catgId) {
for (var i = 0; i < catgs.length; i++) {
if (catgs[i].id === parseInt(catgId)) {
return catgs[i];
}
}
return null;
}
};
});
Need help to replace catgs JSON data to $http request, for example musite.com/jsondata.json
//try this
$http.get('your api url or .json').then(function(result){
$scope.jsonData = result.data;
}, function(err) {
console.log(err);
});
Related
I am trying to plot a graph with Hightchart, my data comes from an REST web service.
I am using angularjs (1.5) to get the data.
my Service look like :
app.factory('ServicesImpl', function($http){
var obj = {};
obj.getData = function(){
return $http.get('http://localhost:8080/chartDepense/');
};
return obj;
});
my controller is :
app.controller('myController', function ($scope, $rootScope, ServicesImpl) {
$scope.chart = ServicesImpl.getData().then(function(r){
return r.data;
});
console.log($scope.chart);
$scope.chartOptions = {
title: {
text: $scope.chart.libelle
},
xAxis: {
categories: $scope.chart.categories ,
title: {
text: 'les X'
}
},
yAxis: {
title: {
text: 'les Y'
}
},
series: [{
data: $scope.chart.peroides
}]
};
});
and I got this :
I don't know can I can get my data in my controller to put in chartConfig?
I have a AngularJS factory 'UserSrvc'. This is responsible for calling a RESTful back end to get and create user accounts using Restangular:
(function () {
'use strict';
angular
.module('myapp')
.factory('UserSrvc', UserSrvc);
function UserSrvc(Restangular) {
return {
getAllUsers: getAllUsers,
getUser: getUser,
saveUser: saveUser
};
/////////////////////
function getAllUsers(){
return Restangular.all('users').getList();
}
function getUser(user){
return Restangular.setFullResponse(true).one('users', user).get();
}
function saveUser(user) {
return Restangular.all('users').post(user);
}
};
})();
My User controller then has functions for initializing the data for loading in to Angular UI Grid as well as functions for saving a user and getting user data:
(function () {
'use strict';
var controllerId = 'UserCtrl';
// Define the controller on the module
// Inject the dependencies.
// Point to the controller definition function.
angular
.module('myapp')
.controller(controllerId, UserCtrl, ['UserSrvc', 'ngDialog', '$log', 'toaster']);
function UserCtrl(UserSrvc, ngDialog, $log, toaster){
// Using the 'Controller As' syntax, so we assign to the vm variable (for view model).
var vm = this;
var allUsers = [];
// Bindable properties and functions are placed on vm.
vm.activate = activate;
vm.allUsers = {};
vm.toggleForm = false;
vm.saveUser = saveUser;
vm.gridOptions = {
data: allUsers,
enableSorting: true,
enableColumnResizing: true,
enableGridMenu: true,
showGridFooter: true,
showColumnFooter: true,
enableFiltering: true,
columnDefs: [
{name: 'firstName', field: 'First'},
{name: 'lastName', field: 'Last'},
{name: 'login', field: 'Login'},
{name: 'email', field: 'Email'}
]
};
activate();
function activate() {
return getUsers().then(function() {
// User Controller is now activated
$log.info('UserCtrl activated');
});
}
function refreshUserTable() {
return UserSrvc.getAllUsers()
.then(function(data) {
// User table refresh
vm.gridOptions.data = data.data;
$log.info('User table data refreshed.', vm.gridOptions.data);
});
}
function getUsers() {
return UserSrvc.getAllUsers()
.then(function (data) {
$log.debug('data: ', data);
vm.gridOptions.data = data;
//allUsers = data;
$log.debug('allUsers: ', vm.gridOptions.data);
return vm.gridOptions.data;
},
function(response) {
$log.debug("Failed to get users, error with status code", response.status);
});
}
function saveUser(vm) {
var new_user = {
"user": {
"First": vm.user.firstname,
"Last": vm.user.surname,
"Login": vm.user.username,
"Password": vm.user.password,
"Email": vm.user.email
}
};
//$log.debug('The user to be saved: ', user);
return UserSrvc.saveUser(new_user)
.then(function (data) {
$log.debug('The user to be saved: ', new_user);
$log.debug('response: ', data);
// Refresh the table
refreshUserTable(vm);
// Reset the user form
resetForm();
// Close the form
vm.toggleForm = !vm.toggleForm;
// Success toast
toaster.pop("success","User saved", "User '" + new_user.user.Login + "' successfully created");
return data;
},
function(response) {
$log.debug("Failed to save user, error with status code", response.status);
toaster.pop("error", "Unable to save user", "Failed to save user, error with status code " + response.status);
});
}
}
})();
On the first call to UserSrvc.getAllUsers() in the getUsers() function the data parameter from the .then(function(data) returns an array like so:
[
{
"Last": "Jobs",
"Email": "test#example.com",
"Login": "jobs",
"id": 1,
"First": "Steve"
}
]
However, subsequent calls made by refreshUserTable() to the same UserSrvc.getAllUsers(), the data parameter from .then(function(data)) returns an object like so:
{
"data": [
{
"Last": "Jobs",
"Email": "test#example.com",
"Login": "jobs",
"id": 1,
"First": "Steve"
}
]
}
To get it to work I need to pull the data array from the data object by doing data.data.
Why is it that subsequent calls made by the refreshUserTable() return an object and not an array? My suspicion is that it has something to do with the way in which I'm using Restangular or is there something glaringly obvious I've missed?
Ideally I'd like to get rid of the refreshUserTable() function and just use the getAllUsers() to refresh the table.
you set setFullResponse to true which extend your response object. You confused because Restangular uses same property key with you data.
If you want to use full response specifically on one method just use withConfig method of Restangular.
Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setFullResponse(true);
});
I'm making an Angular App and I'm starting to use some of the Kendo UI controls. I'm having some issues wiring up the AutoComplete control. I would like to use a factory that will return the list of "auto complete" values from my database.
I have iincluded the auto complete control and I'm trying to use the k-options attribute:
<input kendo-auto-complete ng-model="myFruit" k-options="FruitAutoComplete" />
In my controller the following hard coded list of fruits work:
$scope.FruitAutoComplete = {
dataTextField: 'Name',
dataSource:[
{ id: 1, Name: "Apples" },
{ id: 2, Name: "Oranges" }
]
}
When I move this over to use my factory I see it calling and returning the data from the factory but it never get bound to the screen.
$scope.FruitAutoComplete = {
dataTextField: 'Name',
dataSource: new kendo.data.DataSource({
transport: {
read: function () {
return FruitFactory.getYummyFruit($scope.myFruit);
}
}
})
}
I end up with the request never being fulfilled to the auto complete.
My factory is just returning an array of fruit [
my Fruit Factory Code:
getYummyFruit: function (val) {
return $http.get('api/getFruitList/' + val)
.then(function (res) {
var fruits= [];
angular.forEach(res.data, function (item) {
fruits.push(item);
});
return fruits;
});
}
Here is your solution
http://plnkr.co/edit/iOq2ikabdSgiTM3sqLxu?p=preview
For the sake of plnker I did not add $http (UPDATE - here is http://plnkr.co/edit/unfgG5?p=preview with $http)
UPDATE 2 - http://plnkr.co/edit/01Udw0sEWADY5Qz3BnPp?p=preview fixed problem as per #SpencerReport
The controller
$scope.FruitAutoCompleteFromFactory = {
dataTextField: 'Name',
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
return FruitFactory.getYummyFruit(options)
}
}
})
}
The factory -
factory('FruitFactory', ['$http',
function($http) {
return {
getYummyFruit: function(options) {
return $http.get('myFruits.json').success(
function(results) {
options.success(results);
});
}
}
}
Until now, I have been querying the data stores using Rally App SDK, however, this time I have to update a story using the js sdk. I tried looking up for examples for some sample code that demonstrates how the App SDK can be used to update/add values in Rally. I have been doing CRUD operations using Ruby Rally API but never really did it with the app sdk.
Can anyone provide some sample code or any link to where I could check it out?
Thanks
See this help document on updating and creating reocrds. Below are examples - one updates a story, the other creates a story. There is not much going on in terms of UI: please enable DevTools console to see console.log output.
Here is an example of updating a Defect Collection on a User Story:
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
console.log("launch");
Rally.data.ModelFactory.getModel({
type: 'User Story',
success: this._onModelRetrieved,
scope: this
});
},
_onModelRetrieved: function(model) {
console.log("_onModelRetrieved");
this.model = model;
this._readRecord(model);
},
_readRecord: function(model) {
var id = 13888228557;
console.log("_readRecord");
this.model.load(id, {
fetch: ['Name', 'Defects'],
callback: this._onRecordRead,
scope: this
});
},
_onRecordRead: function(record, operation) {
console.log('name...', record.get('Name'));
console.log('defects...', record.get('Defects'));
if(operation.wasSuccessful()) {
//load store first by passing additional config to getCollection method
var defectStore = record.getCollection('Defects', {
autoLoad: true,
listeners: { load: function() {
//once loaded now do the add and sync
defectStore.add({'_ref':'/defect/13303315495'});
defectStore.sync({
callback: function() {
console.log('success');
}
});
}}
});
}
},
});
Here is an example of creating a user story, setting a project and scheduling for an iteration:
Ext.define('CustomApp', {
extend: 'Rally.app.TimeboxScopedApp',
componentCls: 'app',
scopeType: 'iteration',
comboboxConfig: {
fieldLabel: 'Select an Iteration:',
labelWidth: 100,
width: 300
},
addContent: function() {
this._getIteration();
},
onScopeChange: function() {
this._getIteration();
},
_getIteration: function() {
var iteration = this.getContext().getTimeboxScope().record.get('_ref');
console.log('iteration',iteration);
if (!this.down('#b2')) {
var that = this;
var cb = Ext.create('Ext.Container', {
items: [
{
xtype : 'rallybutton',
text : 'create',
id: 'b2',
handler: function() {
that._getModel(iteration);
}
}
]
});
this.add(cb);
}
},
_getModel: function(iteration){
var that = this;
Rally.data.ModelFactory.getModel({
type: 'UserStory',
context: {
workspace: '/workspace/12352608129'
},
success: function(model) { //success on model retrieved
that._model = model;
var story = Ext.create(model, {
Name: 'story 777',
Description: 'created via appsdk2'
});
story.save({
callback: function(result, operation) {
if(operation.wasSuccessful()) {
console.log("_ref",result.get('_ref'), ' ', result.get('Name'));
that._record = result;
that._readAndUpdate(iteration);
}
else{
console.log("?");
}
}
});
}
});
},
_readAndUpdate:function(iteration){
var id = this._record.get('ObjectID');
console.log('OID', id);
this._model.load(id,{
fetch: ['Name', 'FormattedID', 'ScheduleState', 'Iteration'],
callback: function(record, operation){
console.log('ScheduleState prior to update:', record.get('ScheduleState'));
console.log('Iteration prior to update:', record.get('Iteration'));
record.set('ScheduleState','In-Progress');
record.set('Iteration', iteration);
record.set('Project', '/project/12352608219')
record.save({
callback: function(record, operation) {
if(operation.wasSuccessful()) {
console.log('ScheduleState after update..', record.get('ScheduleState'));
console.log('Iteration after update..', record.get('Iteration'));
}
else{
console.log("?");
}
}
});
}
})
}
});
When I call fetch on my collection the app is calling the server and server returns an array of object. In the success function of the fetch call I've got an empty collection and the original response holding all objects that was responded by the server.
Collection
var OpenOrders = BaseCollection.extend({
model: Order,
url: baseUrl + '/api/orders?status=1'
});
Model
var Order = BaseModel.extend(
{
url:baseUrl + "/api/order",
defaults:{
order_items: new OrderList(),
location: 1,
remark: "remark"
},
initialize: function(options) {
var orderItems = this.get('order_items');
if (orderItems instanceof Array) {
orderItems = new OrderList(orderItems);
this.set({'order_items': orderItems})
}
orderItems.bind('change', _.bind(function() {
this.trigger('change')
}, this))
.bind('remove', _.bind(function() {
this.trigger('change')
}, this));
return this;
},
sum: function() {
return this.get('order_items').sum();
},
validate: function() {
return !!this.get('order_items').length;
},
add:function(product) {
this.get('order_items').add(product);
},
remove: function(product) {
this.get('order_items').remove(product);
}
);
Fetching the collection
this.collection.fetch({success:_.bind( function(collection, response){
console.log('OpenOrdersListView', collection.toJSON())
// logs []
console.log('OpenOrdersListView', response)
// logs [Object, Object ...]
}, this)})
Damm, its the validate method in my model. I've though validate have to return a boolean, but after reading the docs, it has to return an error message only if the model is not valid.
validate: function() {
if (!this.get('order_items').length){
return 'set minium of one product before save the order'
}
},