I can Post data , with first method, but when i am using $resource POST, it doesn't work. Whats wrong with my createInventory function
$scope.addInventory = function(inventory, $location) {
$http.post("http://localhost/api/v1/inventory/", inventory)
.success(function(data) {
$scope.info.objects.key = data;
$location.path('/inventory');
});
};
And with this method it doesnt work at all
$scope.createInventory = function(){
Inventory.create($scope.info);
$location.path('/inventory/add/');
};
Here goes the template
<label>Name</label>
<input class="form-control" type="text" ng-model="inventory.name" /><br />
<label>Slug</label>
<input class="form-control" type="text" ng-model="inventory.slug" /><br />
<label>Description</label>
<input class="form-control" type="text" ng-model="inventory.description" /><br />
<label>Category</label>
<select ng-show="!show" ng-model="inventory.category" ng-options="category.name for category in category.objects">
<option value="" selected>--Please select your category--</option>
</select>
<input type="button" class="btn btn-primary" ng-click="createInventory()" value="Save" />
I have ng-repeat defined in other template
ng-repeat="inventory in info.objects"
Here if needed is my factory
app.factory('Category', function($resource, $http) {
return $resource('http://localhost/api/v1/category/:id/', {},
{
update: {
method: 'POST',
isArray: false
},
save: {
method: 'PUT'
},
query: {
method: 'GET',
isArray: false
},
create: {
method: 'POST'
},
drop: {
method: 'DELETE',
params: {id: '#id'}
}
}
);
});
Entire controller
app.controller('InventoryCtrl', function($scope, $http, Inventory, Category, $location) {
$scope.createInventory = function(){
Inventory.create($scope.info);
$location.path('/inventory/add/');
};
$scope.info = Inventory.query();
$scope.category = Category.query();
$scope.addInventory = function(inventory, $location) {
$http.post("http://api.bos.lv/api/v1/inventory/", inventory)
.success(function(data) {
$scope.info.objects.key = data;
});
};
});
my api
{
meta: {
limit: 20,
next: null,
offset: 0,
previous: null,
total_count: 2
},
objects: [
{
category: {},
count: 1,
created: "2014-02-27T16:23:40.813690",
description: "asd",
id: 50,
location: "asd",
name: "asd",
resource_uri: "/api/v1/inventory/50",
slug: "asd",
status: "Broken"
},
{
category: {},
count: 1,
created: "2014-02-27T16:46:05.017178",
description: "asd",
id: 51,
location: "sad",
name: "bubu",
resource_uri: "/api/v1/inventory/51",
slug: "bubu",
status: "Broken"
}
]
}
I'm guessing you need to wait for the post to finish before you can move to another location... so you need to change the path on the callback.
$scope.createInventory = function(){
Inventory.create($scope.info, function(param) {
$location.path('/inventory/add/');
);
};
Related
I'm using AngularJS framework.
I have a text box to enter an amount and a drop down to select a type.
<input type="text" ng-model="user.amount"/>
<select ng-model="user.rateType">
<option> rate </option>
<option> unrate</option>
</select>
<input type="text" ng-model="user.assignVal"/>
Here is my controller
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.Main = [
{ id: "1", hval: 1000, lval: 5000, type: "rate", cal: "20" },
{ id: "2", hval: 6000, lval: 10000, type: "rate", cal: "50" },
{ id: "3", hval: 1000, lval: 5000, type: "unrate", cal: "100" },
{ id: "4", hval: 6000, lval: 10000, type: "unrate", cal: "100" },
];
console.log($scope.user.assignVal);
});
The user enter an amount in the text-box and select the rate type.
I need to find the element fulfilling the following conditions :
the user selected type matches item type
the amount entered by the user is in the range delimited by hval andlval
For example,
User enters 1100 as amount and select rate type, cal equals 20
User enters 6500 as amount and select rate type, cal equals 50
User enters 1100 as amount and select unrate type, cal equals 100
How can I achieve this ?
get request
$scope.loadShareSetting = function (){
$http({
method: "GET",
headers: { 'Content-Type': 'application/json','Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')},
url: appConfig.apiUrl + "/residence-settings",
}).then(function (response) {
$scope.residenceSetting = response.data;
}, function (response) {
});
}
Here is a sample code to achieve this
angular.module("myApp", []);
angular
.module("myApp")
.controller("myController", [
"$scope",
"myService",
function ($scope, myService) {
$scope.getCalForAmount = function () {
var result = myService.getCalForAmount($scope.amount, $scope.type);
if (result !== -1) {
$scope.calForAmount = result.cal;
} else {
$scope.calForAmount = ""; // no matching cal, empty field
}
};
},
])
.service("myService", function () {
var items = [
{ id: "1", hval: 1000, lval: 5000, type: "rate", cal: "20" },
{ id: "2", hval: 6000, lval: 10000, type: "rate", cal: "50" },
{ id: "3", hval: 1000, lval: 5000, type: "unrate", cal: "100" },
{ id: "4", hval: 6000, lval: 10000, type: "unrate", cal: "100" },
];
return {
getCalForAmount: function (amount, type) {
var result = items.find(function (item) {
return (
/^[0-9]*$/.test(amount) && // amount must be an number
type === item.type && // type must match
amount >= item.hval && // amount is in the range delimited by hval
amount <= item.lval // and lval
);
});
return result || -1;
},
};
});
label {
display: block;
padding: 5px;
}
label span {
display: inline-block;
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<html ng-app="myApp">
<body>
<div ng-controller="myController">
<label>
<span>Amount</span>
<input type="text" ng-model="amount" ng-change="getCalForAmount()" />
</label>
<label>
<span>Type</span>
<select ng-model="type" ng-change="getCalForAmount()">
<option>rate</option>
<option>unrate</option>
</select>
</label>
<label>
<span>Cal for amount and type</span>
<input type="text" ng-model="calForAmount" readonly />
</label>
</div>
</body>
</html>
Edit
Checkout this demo on Plunker to understand how to load items using http request
I am a little new to AngularJS but I cannot figure out why the ng-click here will not call th addingSt() function, I wonder if it has something to do with the fact that it is being called from a mdDialog. Thanks for your help.
Heres my html for the mdDialog:
<md-dialog aria-label="Send Email">
<md-dialog-content>
<h3>Issue Details</h3>
<h4>Description</h4>
<md-input-container>
<label>Add description:</label>
<textarea class="form-control input-lg" style="width: 500px; height:100px;"></textarea>
</md-input-container>
<h3>Sub-tasks:</h3>
<md-list-item ng-repeat=" subtask in subtasks">
<p>{{subtask.content}}</p>
<md-checkbox aria-label="blarg" class="md-secondary" style="padding-right:60px;" ng-click="removeSubTask(subtask,$index)"></md-checkbox>
<md-list-item ng-if="addingTask === true"> <input ng-if="addingTask===true" ng-model="task.content" aria-label="blarg" placeholder="Add Subtask Here"></input>
</md-dialog-content>
<md-dialog-actions>
<md-button ng-show="addingTask === false" ng-click="addingSt()" class="btn btn-primary">
Add Sub-Task
</md-button>
<md-button ng-show="addingTask === true" ng-click="addingSt()" class="btn btn-primary">
cancel
</md-button>
<md-button ng-show="addingTask === true" ng-click="addSubTask()" class="btn btn-primary">
Submit
</md-button>
<md-button ng-click="closeDialog()" class="btn btn-primary">
Close
</md-button>
Here's the controller for the parent of the above mdDialog, (the controller for the mdDialog is nested inside it and works fine for all functions accept the addingSt() function)
var app = angular.module('epr')
app.controller('adminMainCtr',[ '$scope','$mdDialog',function($scope, $mdDialog) {
$scope.issues = [
{ name: 'Blizzard', img: 'img/100-0.jpeg', WardMessage: true, index:0, subtasks:[{content:"Shovel Sister Pensioner's Driveway "},
{content:"Clear downed trees at the Bush's home "}]},
{ name: 'Tornado', img: 'img/100-1.jpeg', WardMessage: false, index:1, subtasks:[{content:"",index:0}] },
{ name: 'Peterson Family Car Crash', img: 'img/100-2.jpeg', WardMessage: false, index:2, subtasks:[{content:"",index:0}] },
{ name: 'Flood', img: 'img/100-2.jpeg', WardMessage: false, index:3, subtasks:[{content:"",index:0}] },
{ name: 'School Shooting', img: 'img/100-2.jpeg', WardMessage: false, index:4, subtasks:[{content:"",index:0}] }
];
$scope.goToIssue = function(issue, event) {
var parentEl = angular.element(document.body);
$mdDialog.show({
//parent: parentEl,
templateUrl:'views/issue.html',
locals: {
items: $scope.items,
issue: issue
},
controller: DialogController
});
function DialogController($scope, $mdDialog) {
$scope.subtasks = issue.subtasks;
$scope.addingTask = false;
$scope.task={content:""};
$scope.closeDialog = function() {
console.log($scope.addingTask);
$mdDialog.hide();
}
$scope.removeSubTask = function(subtask,index){
$scope.subtasks.splice(index,1);
}
}
$scope.addSubTask = function() {
console.log("here");
}
$scope.addingSt = function() {
if($scope.addingTask === false) {
console.log($scope.addingTask);
$scope.addingTask = true;
return;
}
if($scope.addingTask === true) {
$scope.addingTask = false;
return;
}
}
}
}]);
Any help that you can lend me would be very appreciated!!!
You messed with the HTML and angylar code.
Errors found:
1) angular module initialization.
var app = angular.module('MyApp', ['ngMaterial'])
2) You placed some function outside the DialogController
3) md-list-item HTML has no end tags.
Created working Plunkr here. https://plnkr.co/edit/Sl1WzLMCd8sW34Agj6g0?p=preview . Hope it will solve your problem.
(function() {
'use strict';
var app = angular.module('MyApp', ['ngMaterial'])
app.controller('adminMainCtr', ['$scope', '$mdDialog', function($scope, $mdDialog) {
$scope.issues = [{
name: 'Blizzard',
img: 'img/100-0.jpeg',
WardMessage: true,
index: 0,
subtasks: [{
content: "Shovel Sister Pensioner's Driveway "
}, {
content: "Clear downed trees at the Bush's home "
}]
}, {
name: 'Tornado',
img: 'img/100-1.jpeg',
WardMessage: false,
index: 1,
subtasks: [{
content: "",
index: 0
}]
}, {
name: 'Peterson Family Car Crash',
img: 'img/100-2.jpeg',
WardMessage: false,
index: 2,
subtasks: [{
content: "",
index: 0
}]
}, {
name: 'Flood',
img: 'img/100-2.jpeg',
WardMessage: false,
index: 3,
subtasks: [{
content: "",
index: 0
}]
}, {
name: 'School Shooting',
img: 'img/100-2.jpeg',
WardMessage: false,
index: 4,
subtasks: [{
content: "",
index: 0
}]
}];
$scope.goToIssue = function(issue, event) {
var parentEl = angular.element(document.body);
$mdDialog.show({
templateUrl: 'mddialog.html',
locals: {
message: {
items: $scope.items,
issue: issue
}
},
controller: DialogController
});
}
function DialogController($scope, $mdDialog, message) {
console.log(message)
//$scope.subtasks = message.issue.subtasks;
$scope.addingTask = false;
$scope.task = {
content: ""
};
$scope.closeDialog = function() {
console.log($scope.addingTask);
$mdDialog.hide();
}
$scope.removeSubTask = function(subtask, index) {
$scope.subtasks.splice(index, 1);
}
$scope.addSubTask = function() {
console.log("here");
}
$scope.addingSt = function() {
if ($scope.addingTask === false) {
console.log($scope.addingTask);
$scope.addingTask = true;
return;
}
if ($scope.addingTask === true) {
$scope.addingTask = false;
return;
}
}
}
}]);
})();
I am using Mongodb. When I want to update fields I am getting the following error Cast to ObjectId failed for the value:
[object Object],[object Object],[object Object].
When post is empty let me to update all the properties while somebody post somethings then I am not able to update provider properties and I am getting following error:
View which have used modal from ui bootstapt.
<label class="col-lg-2 control-label">Company Name</label>
<div class="col-lg-10">
<input name="name" type="text" ng-model="provider.name" minlength="4" class="form-control" placeholder="Amazon Web Services" required>
<span class="help-block" ng-show="cspRegister.name.$dirty && cspRegister.name.$invalid"> Not valid name!</span>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Abbreviated company name</label>
<div class="col-lg-10">
<input name="abbreviated" type="text" ng-model="provider.abbreviated" class="form-control" placeholder="AWS" >
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Home page</label>
<div class="col-lg-10">
<input name="url" type="url" ng-model="provider.url" class="form-control" placeholder="http://aws.amazon.com/" required>
<span class="help-block" ng-show="cspRegister.url.$error.url"> Not valid url!</span>
</div>
</div>
<!--start point of muli select-->
<div class="form-group">
<label class="col-lg-2 control-label">Product name</label>
<div class="col-lg-10">
<select name="services" multiple ng-model="provider.services" class="form-control" required >
<option value="paas">Paas</option>
<option value="saas">Saas</option>
<option value="dbaas">Dbaas</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Location</label>
<div class="col-lg-10">
<select multiple ng-model="provider.locations" class="form-control" class="form-control" required>
<option ng-repeat="item in locations" value="{{item.name}}">{{item.name}}</option>
</select>
<span class="help-block">A longer block of help text that breaks onto a new line and may extend beyond one line.</span>
</div>
</div>
<!--end of multi selector-->
<div class="form-group">
<label class="col-lg-2 control-label">Description</label>
<div class="col-lg-10">
<textarea name="description" ng-model="provider.description" class="form-control" rows="3" required></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button ng-click="updateProvider(provider);ok()" class="btn btn-success"><i class="icon-white icon-plus"></i> Update & Close</button>
<button ng-click="cancel()" class="btn btn-warning">Cancel</button>
</div>
Provider Schema
var ProviderSchema = new Schema({
name: String,
abbreviated: String,
// company:String,
services: {type : Array, default:[]},
locations: {type : Array, default:[]},
description: String,
url: String,
author: String,
upvotes: { type:Number, default:0 },
upvoteUser:{type : Array, default:[]},
createdOn: { type: Date, default: Date.now },
certificates:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Certificates' }],
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
});
ProviderSchema.methods.findByName = function (cb) {
return this.model('Provider').find({ name: this.name }, cb);
}
ProviderSchema.methods.upvote = function(cb) {
this.upvotes += 1;
this.save(cb, function(error) {
if(error){
console.error("Error saving object: ", error)
}
});
};
This is update in factory
ob.updateProvider = function (provider) {
return $http.put('/api/providers/' + provider._id , provider, {
headers: {Authorization: 'Bearer '+Auth.getToken()}
}).success(function(provider){
})
};
and this is update function in my api
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Provider.findById(req.params.id, function (err, provider) {
if (err) { return handleError(res, err); }
if(!provider) { return res.send(404); }
var updated = _.merge(provider, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, provider);
});
});
};
This is what I have in my controller.
$scope.updateProvider = function (updatedProvider) {
var provider = updatedProvider;
providers.updateProvider(provider)
.success(function () {
providers.getAll();
$scope.status = 'Updated provider! Refreshing provider list.';
})
.error(function(err, status) {
console.log(err);
console.log(status);
});
};
This is what is result for updated:
abbreviated: 'aws',
_id: 55663fc20e9009c82dccba94,
company: 'http://dbpedia.org/resource/SnapLogic',
name: 'SnapLogic',
description: 'SnapLogic is a commercial software company that provides data an
2006. SnapLogic is headed by Ex-CEO and Co-Founder of Informatica, Gaurav Dhill
__v: 25,
posts:
[ { upvotes: 4,
upvoteUser: [Object],
comments: [Object],
__v: 16,
author: 'Juan y Maryam',
body: 'cc',
title: 'cczzs',
_id: '5569f716a4c7bbd4219a3303' },
{ upvotes: 4,
upvoteUser: [Object],
comments: [],
__v: 4,
author: 'Juan y Maryam',
body: 'zzaaa',
title: 'juan',
_id: '5569fb10c61b1af02fa1cc39' },
{ upvotes: 4,
upvoteUser: [Object],
comments: [],
__v: 4,
author: 'Juan y Maryam',
body: 'xxxxx',
title: 'xxxxxxxxxx',
_id: '5569fb15c61b1af02fa1cc3a' },
{ upvotes: 2,
upvoteUser: [Object],
comments: [],
__v: 2,
author: 'Test User',
body: 'nnnnnnnnnnnnnnnn',
title: 'ooooooooooooo',
_id: '5569fcd3335d49d82ccef9cd' },
{ upvotes: 1,
upvoteUser: [Object],
comments: [],
__v: 1,
author: 'Editor',
body: 'ss',
title: 'sssssss',
_id: '556a07892d62dadc182fcc1f' },
{ upvotes: 1,
upvoteUser: [Object],
comments: [],
__v: 1,
author: 'maya beaty',
body: 'ssssssss',
title: 'ssssssss',
_id: '556a07f92d62dadc182fcc23' },
{ upvotes: 1,
upvoteUser: [Object],
comments: [],
__v: 1,
author: 'Maryam Pashmi',
body: 'z',
title: 'z',
_id: '556a13e62848566023f03e6d' },
556a07f92d62dadc182fcc23,
556a13e62848566023f03e6d ],
certificates: [],
createdOn: Thu May 28 2015 00:05:54 GMT+0200 (Romance Daylight Time),
upvoteUser: [ 'maya beaty', 'Maryam Pashmi', 'Juan y Maryam' ],
upvotes: 3,
locations: [ 'Åland Islands', 'Albania' ],
services: [ 'saas' ] }
PUT /api/providers/55663fc20e9009c82dccba94 500 10ms
Is there any one who know why I am getting this error and what issue I have to change in my schema?
I don't have a solution but I can try to explain what the problem is, or at least why it isn't working in your case. Although there's couple of solutions at the end that may or may not work..
Your provider.posts is an array of another set of documents referenced by "Posts", as defined in your Provider schema.
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
posts: [
{upvotes: 4, ... title: 'cczzs', _id: '5569f716a4c7bbd4219a3303' },
{upvotes: 4, ... title: 'juan', _id: '5569fb10c61b1af02fa1cc39' },
{upvotes: 4, ... _id: '5569fb15c61b1af02fa1cc3a' },
...
{upvotes: 1, _id: '556a13e62848566023f03e6d' },
556a07f92d62dadc182fcc23,
556a13e62848566023f03e6d
],
These are actually supposed to be saved as just IDs (556a07…), because that's how they're defined in your Schema
Actually if you look towards the end there are some elements which are actually just IDs (556a07f92d62da…), those are probably the ones fetched from the database, and the others are _.merged from req.body
The problem is that when saving, these objects are being converted to string "[Object object]" for some reason. This isn't supposed to happen or at least doesn't happen with me. I have mongoose#3.8 installed, so check if maybe you're on an older version.
Just to make sure this is exactly the root cause of the problem, you should
delete req.body.posts;
var updated = _.merge(provider, req.body);
// now updates.posts should only have 2 IDs mentioned above
updated.save(...
and see if it gets saved.
Anyways going through older questions you'll find some have had luck with deleting and re-creating the entire collection. Some advise that it's bad idea to store them as objects in the first place, in which case you can actually .map these objects and convert them to their native string ID or ObjectID before saving.
updated.posts = updated.posts.map(function(post){return post._id});
updated.save(...
Hope that helps out in some way even if it doesn't solve it.
This is the code I'm using (and have been using throughout the whole project), the scope is updated but ng-repeat wont refresh and I'm using scope.$apply.. Have no idea why, few devs also took a look at the code.. no solution..
Directive:
app.directive("addBrandSettings", function(){
return {
restrict: "A",
link: function(scope, element, attrs){
element.bind("keypress", function(e){
if(e.which === 13){
var brand = element.val();
scope.$apply(function(){
scope.settings.brands.push(brand);
console.log(scope.settings.brands);
})
element.val("");
}
})
}
}
});
HTML:
<input add-brand-settings type="text" placeholder="Add Brand"/>
<p ng-repeat="brand in settings.brands">{{brand}}<a remove-brand-settings index="{{$index}}" href="#"><i class="fa fa-times-circle"></i></a></p>
Scope:
$scope.settings = {
companyInfo: {
name: "",
email: "",
phone: "",
website: ""
},
users: [
{
username: "Supreme Manager",
role: "Super User",
password: "asdasd"
},
{
username: "Regular Grunt",
role: "User",
password: "asdasd"
}
],
brands: [
"Maxi",
"Chipsy",
"Bananice"
],
retailers: [
"Maxi",
"Ikea",
"Tempo"
]
}
Your code works perfectly, so you probably have some syntax problem or something, here's a working example:
var app=angular.module('App', []);
function ctrl($scope){
$scope.settings = {
companyInfo: {
name: "",
email: "",
phone: "",
website: ""
},
users: [
{
username: "Supreme Manager",
role: "Super User",
password: "asdasd"
},
{
username: "Regular Grunt",
role: "User",
password: "asdasd"
}
],
brands: [
"Maxi",
"Chipsy",
"Bananice"
],
retailers: [
"Maxi",
"Ikea",
"Tempo"
]
}
}
app.directive("addBrandSettings", function(){
return {
restrict: "A",
link: function(scope, element, attrs){
element.bind("keypress", function(e){
if(e.which === 13){
var brand = element.val();
scope.$apply(function(){
scope.settings.brands.push(brand);
console.log(scope.settings.brands);
})
element.val("");
}
})
}
}
});
html:
<div ng-app="App" ng-controller="ctrl">
<input add-brand-settings type="text" placeholder="Add Brand"/>
<p ng-repeat="brand in settings.brands">{{brand}}<a remove-brand-settings index="{{$index}}" href="#"><i class="fa fa-times-circle"></i></a></p>
</div>
Live example :http://jsfiddle.net/choroshin/7zVd2/
I am new to angularjs and want to create the model array when i click the checkbox and below is my code..
$scope.selectedAlbumSongs = [{
'name': 'song1',
'url': 'http://test/song1.mp3'
}, {
'name': 'song2',
'url': 'http://test/song2.mp3'
}, {
'name': 'song3',
'url': 'http://test/song3.mp3'
}];
$scope.playList = {};
HTML:
<fieldset data-role="controlgroup">
<legend>Select songs to play</legend>
<label ng-repeat="song in selectedAlbumSongs">
<input type="checkbox" name="{{song.url}}" id="{{song.name}}" ng-model="playList[song.url]">
<label for="{{song.name}}">{{song.name}}</label>
</label>
</fieldset>
The above code updating the playList as shown below when i click the checkbox
{
"http://test/test1.mp3": true,
"http://test/test2.mp32": true,
"http://test/test3.mp3": false
}
But I want to create the ng-model in the below format, and remove the object when the checkbox is unchecked (for ex. if the uncheck the song3, the song3 object removed from the array). Can you tell me how can write this logic?
Expected:
[{
name: "song1",
url: "http://test/song1.mp3"
}, {
name: "song2",
url: "http://test/song2.mp3"
}]
You can do it like this:
$scope.selectedAlbumSongs = [ { 'name': 'song1', 'url': 'http://test/song1.mp3' }, { 'name': 'song2', 'url': 'http://test/song2.mp3' }, {'name': 'song3', 'url': 'http://test/song3.mp3' }];
$scope.selectedSongs = function () {
$scope.playList = $filter('filter')($scope.selectedAlbumSongs, {checked: true});
}
Then, simple call selectedSongs() when the selection is changed:
<input type="checkbox" name="{{song.url}}" id="{{song.name}}" ng-model="song.checked" ng-change="selectedSongs()">
See demo here