I am using MEAN JS, i am trying to edit the list items on the list page, but it shows the error as below. i have initiated the data using ng-init="find()" for the list and ng-init="findOne()" for individual data.
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
HTML
Below i the form inside the controller where it initiates the find() and findOne().
<div ng-controller="OrdersController" ng-init="find()">
<div>
<div class="order-filter">
<div ng-repeat="order in orders">
<form ng-init="findOne()" name="orderForm" class="form-horizontal" ng-submit="update(orderForm.$valid)" novalidate>
<input type="text" class="" ng-model="order.title">
<input type="text" class="" ng-model="order.content">
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
Controller
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = $scope.order;
order.$update(function () {
$location.path('orders/' + order._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function () {
Orders.query(function loadedOrders(orders) {
orders.forEach(appendFood);
$scope.orders = orders;
});
};
$scope.findOne = function () {
$scope.order = Orders.get({
orderId: $stateParams.orderId
});
};
You need to check your Orders Service which probably is using $resource to provide your API requests (Orders.query)
It should look something like this:
function OrdersService($resource) {
return $resource('api/orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
The style may be different depending on which version of mean you're using. By default, the $resource query will expect an array of results, but if for some reason you've set "isArray" to false then it will expect an object.
https://docs.angularjs.org/api/ngResource/service/$resource
I am working on a project where I need to fetch data from API and display it on HTML page using Angularjs
API is returning me the Categories details. Here is my API
http://naazexpress.com/category.php
this is my angularjs Code
var app = angular.module('appControllers', [])
app.controller('ProductCtrl', function($scope, srvShareData,$http) {
// alert('product Controller');
$http.get("http://naazexpress.com/category.php")
.then(function (response) {
$scope.data = response.data.children;
console.log(response);
});
console.log('aa');
// alert($scope.data);
$scope.sharedData = srvShareData.getData();
console.log($scope.sharedData);
});
app.service('srvShareData', function($window) {
var KEY = 'App.SelectedValue';
// alert('ssss');
var addData = function(newObj) {
var mydata = $window.sessionStorage.getItem(KEY);
console.log(mydata);
if (mydata) {
mydata = JSON.parse(mydata);
} else {
mydata = [];
}
mydata = newObj;
console.log(mydata);
// mydata.push(newObj);
$window.sessionStorage.setItem(KEY, JSON.stringify(mydata));
};
var getData = function(){
var mydata = $window.sessionStorage.getItem(KEY);
if (mydata) {
mydata = JSON.parse(mydata);
}
return mydata || [];
};
return {
addData: addData,
getData: getData
};
});
and I am implementing it in my HTML page
here is my HTML page
<div id="login-page" class="row" ng-app="starter">
<div class="col s12 z-depth-6 card-panel">
<form class="login-form" id="login">
<div class="row">
<div class="input-field col s12 center">
<img src="http://naazexpress.com/skin/frontend/default/jm_casual/images/logo.png" alt="" class="responsive-img valign profile-image-login">
<p class="center login-form-text">Seller - NaazExpress</p>
</div>
</div>
<div class="input-field col s12 m6" ng-controller="ProductCtrl">
<ul ng-repeat="item in data">
<li>{{item.name}}</li>
</ul></div>
</div></div>
when i run this program the API is not returning anything. is there any issue in the code ? please help
Try This.
$http.get("http://naazexpress.com/category.php")
.then(function (response) {
$scope.data = response.data.children;
console.log(response.data);
});
Your response doesn't have property "children"
Here is the response, it has property "category" and then this "category" has "children"
{"category":{"category_id":"1","parent_id":"0","name":"Root Catalog","is_active":null,"position":"0","level":"0","children":[{"category_id":"2","parent_id":"1","name":"Default Category","is_active":"1","position":"1","level":"1","children":[{"category_id":"3","parent_id":"2","name":"New arrivals","is_active":"1","position":"1","level":"2","children":[{"category_id":"10","parent_id":"3","name":"New","is_active":"1","position":"2","level":"3","children":[]},{"category_id":"11","parent_id":"3","name":"Tops","is_active":"1","position":"3","level":"3","children":[]},{"category_id":"12","parent_id":"3","name":"Bottoms","is_active":"1","position":"4","level":"3","children":[]},{"category_id":"13","parent_id":"3","name":"Denim","is_active":"1","position":"5","level":"3","children":[]},{"category_id":"14","parent_id":"3","name":"Outerwear","is_active":"1","position":"6","level":"3","children":[]},{"category_id":"15","parent_id":"3","name":"Shoes","is_active":"1","position":"7","level":"3","children":[]},{"category_id":"16","parent_id":"3","name":"Jackets","is_active":"1","position":"8","level":"3","children":[]},{"category_id":"17","parent_id":"3","name":"Accessories","is_active":"1","position":"9","level":"3","children":[]}]},{"category_id":"4","parent_id":"2","name":"Women","is_active":"1","position":"2","level":"2","children":[{"category_id":"18","parent_id":"4","name":"New","is_active":"1","position":"1","level":"3","children":[]},{"category_id":"19","parent_id":"4","name":"Tops","is_active":"1","position":"2","level":"3","children":[]},{"category_id":"20","parent_id":"4","name":"Bottoms","is_active":"1","position":"3","level":"3","children":[]},{"category_id":"21","parent_id":"4","name":"Denim","is_active":"1","position":"4","level":"3","children":[]},{"category_id":"22","parent_id":"4","name":"Outerwear","is_active":"1","position":"5","level":"3","children":[]},{"category_id":"23","parent_id":"4","name":"Shoes","is_active":"1","position":"6","level":"3","children":[]},{"category_id":"24","parent_id":"4","name":"Jackets","is_active":"1","position":"7","level":"3","children":[]},{"category_id":"25","parent_id":"4","name":"Accessories","is_active":"1","position":"8","level":"3","children":[]}]},{"category_id":"5","parent_id":"2","name":"Men","is_active":"1","position":"3","level":"2","children":[]},{"category_id":"6","parent_id":"2","name":"Accessories","is_active":"1","position":"4","level":"2","children":[]},{"category_id":"7","parent_id":"2","name":"Sale","is_active":"1","position":"5","level":"2","children":[]},{"category_id":"26","parent_id":"2","name":"Men2","is_active":"1","position":"6","level":"2","children":[]}]}]}}
So try this
response.data.category.children;
On Ajax call from Angular controller, i am passing a complex object as data. On MVC controller object has all null values.
I have MVC view as given below, which will be the boiler plate for Register customer View.
<div data-ng-app="customer" id="customer" data-ng-controller="rootViewModel">
<h2>{{ pageHeading }}</h2>
<hr />
<form id="formElement">
<div ng-view></div>
</form>
Using AngularJS, I will be loading the register customer view, mark of register customer view given below. I have register customer function tied to button using ng-click directive.
<fieldset class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-3">Company Name</label>
<div class="col-sm-4">
<input class="form-control inputfieldValidation" ng-model="customer.Name" type="text" placeholder="Full company name" required autofocus />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">PAN</label>
<div class="col-sm-4">
<input class="form-control" ng-model="customer.Pan" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">TIN</label>
<div class="col-sm-4">
<input class="form-control inputfieldValidation" ng-model="customer.Tin" type="text" required />
</div>
</div>
<button class="btn btn-primary proceedNext" id="registerCompany" ng-click="registerCompany(customer)">Register Customer</button>
</fieldset>
I have angular controller, which has function called registerCustomer() that will be called on click of register customer. I have an ajax call inside that function as given below.
customerModule.controller("CustomerRegistration", function ($scope) {
var initialize = function () {
}
$scope.registerCompany = function (customer) {
$.ajax({
url: 'Home/RegisterCompany',//make sure url exist
data: JSON.stringify({company: customer}),//pass data to action
type:'POST',
success: function (data) {
alert(JSON.stringify(data));
//window.location.href = '#Url.Action("Order")'; //redirect
}
});
}
initialize();
});
On MVC, i have a model called Company as given below.
public class Company
{
public string Name;
public string Pan;
public string Tin;
}
and my MVC controller look as
[HttpPost]
public JsonResult RegisterCompany(Company company)
{
//Do something
return null;
}
Always I have null object on MVC controller, please help me if am missing anything. Thanks in advance
EDIT: It looks like you need a view model in mvc or a modification to your post:
public class CompanyViewModel {
public Company company { get; set; }
}
Or use data: JSON.stringify(customer) instead of data: JSON.stringify({ company: customer })
Here is a working example from a website we are developing. It uses Riot.js instead of angular, but the concepts will be similar.
See also http://www.abeautifulsite.net/postjson-for-jquery/
$.getJSON(self.baseUrl + "/SaveApplicant", $('form.#applicant').serialize(), function (response) {
if (response.errorMessage) {
RiotControl.trigger('error_message', response.errorMessage);
return;
} else {
self.packageQuote.applicant = response;
}
RiotControl.trigger("continue","applicant");
});
Or using post, per the link above
$.post(self.baseUrl + "/SaveApplicant", $('form.#applicant').serialize(), function (response) {
if (response.errorMessage) {
RiotControl.trigger('error_message', response.errorMessage);
return;
} else {
self.packageQuote.census = response;
}
RiotControl.trigger("continue","applicant");
},'json');
There is a bit more involved on the MVC side of things, to send back a json response with lower case property name prefixes:
public ActionResult SaveApplicant(Applicant model)
{
if (ModelState.IsValid)
{
var applicant = DbContext.Applicants.FirstOrDefault(row => row.Id == model.Id);
if (applicant == null) {
DbContext.Applicants.Add(model);
} else {
applicant.Clone(model); // implement as needed or use entity state modified.
}
DbContext.SaveChanges();
return FormattedJsonResult(applicant);
}
return ModelErrors();
}
public ActionResult FormattedJsonResult(object model)
{
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
var result = JsonConvert.SerializeObject(model, camelCaseFormatter);
return Content(result, "application/json");
}
public ActionResult ModelErrors()
{
return FormattedJsonResult(
new
{
errorMessage =
String.Join("\n",
ModelState.Values.SelectMany(value => value.Errors).Select(error => error.ErrorMessage))
});
return View();
}
How can I pass the information from an input field in the front end(using angularjs) as a JSON object to a server(javascript)?
Basically what I intend to do is take input from a user, and pass it as a query to search a database and return the values.
My controller code:
`app.controller('SearchController',['$scope','$http',function($scope,$http){
$scope.click=function(){
var data=$scope.query1;
$http.post('/credjson',data);
/*$scope.addRowAsyncAsJSON = function(){
$scope.cred.push({ 'query':$scope.query1 });
var dataObj = {
query : $scope.query1,
};
var res = $http.post('/credjson', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
$scope.query1='';*/`
Note: The code in between /* */ was a different attempt at trying this out.
My view code:
`<div style="padding-top:20px" ng-controller="SearchController">
<form name="form1" ng-submit="click()">
<input id="creditq" ng-model='query1' type="text" />
<button id="Search" ng-value='Search'>Search</button><br/><br/>
</form>
</div>`
Just construct your JSON payload and pass it to $http as the second param
data: { query1: $scope.query1 }
and then
$http.post('/credjson',data);
I am using angularFire and trying to save data from a form to firebase with $add. Any help would be greatly appreciated. The console logs all work, I am able to retrieve the data in the console. Sorry for all of the code... I wanted to be sure I provided all the material needed.
app.js:
var creativeBillingApp = angular.module('creativeBillingApp', ['ngRoute', 'firebase']);
creativeBillingApp.constant('FIREBASE_URI', "https://XXXX.firebaseIO.com/");
creativeBillingApp.controller('MainCtrl', ['$scope', 'groupsService', function( $scope, groupsService, $firebase ) {
console.log('Works')
$scope.newGroup = {
name: '',
status: ''
};
$scope.addGroup = function(newGroup){
console.log(newGroup);
groupsService.addGroup();
$scope.newGroup = {
name: '',
status: ''
};
};
$scope.updateGroup = function (id) {
groupsService.updateGroup(id);
};
$scope.removeGroup = function(id) {
groupsService.removeGroup(id);
};
}]);
creativeBillingApp.factory('groupsService', ['$firebase', 'FIREBASE_URI',
function ($firebase, FIREBASE_URI) {
'use strict';
var ref = new Firebase(FIREBASE_URI);
return $firebase(ref).$asArray();
var groups = $firebase(ref).$asArray();
var getGroups = function(){
return groups;
};
var addGroup = function (newGroup) {
console.log(newGroup)
groups.$add(newGroup);
};
var updateGroup = function (id){
groups.$save(id);
};
var removeGroup = function (id) {
groups.$remove(id);
};
return {
getGroups: getGroups,
addGroup: addGroup,
updateGroup: updateGroup,
removeGroup: removeGroup,
}
}]);
index.html:
<form role="form" ng-submit="addGroup(newGroup)">
<div class="form-group">
<label for="groupName">Group Name</label>
<input type="text" class="form-control" id="groupName" ng-model="newGroup.name">
</div>
<div class="form-group">
<label for="groupStatus">Group Status</label>
<select class="form-control" ng-model="newGroup.status">
<option value="inactive">Inactive</option>
<option value="active">Active</option>
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
This is the error I am getting:
TypeError: undefined is not a function
at Scope.$scope.addGroup (http://localhost:9000/scripts/app.js:35:19)
and the app.js line 35 is in reference to groupsService.addGroup(); from the app.js code given above.
Firstly, you are returning in your service after you create your $FirebaseArray. You are also creating another $FirebaseArray after that.
return $firebase(ref).$asArray();
Remove that return statement. That is causing your service to return early and none of the attached methods will apply to your service.
In groupService.addGroup() you are calling push, which is not a function on $asArray. You need to call .$add(). The newGroup argument is also not being passed in the controller.
The $.push method is available on the base of the $firebase binding. When you using a $FirebaseArray the $add method pushes a new record into Firebase.
See the docs for more info.
Plunker Demo
var addGroup = function (newGroup) {
console.log(newGroup)
groups.$add(newGroup);
};
Then in your controller you can simply call:
$scope.addGroup = function(newGroup){
groupsService.addGroup(newGroup);
$scope.newGroup = {
name: '',
status: ''
};
};