angular $resource methods dont send the right value - angularjs

this is my service
.factory('ProductData', ['$resource', function($resource) {
return $resource('product/:id', {id: '#id'}, {
'update': { method:'PUT' },
'insertNew': { method:'POST' },
'delete': { method:'DELETE' },
});
}]);
and this is in my conroller
$scope.updateProduct = function(item) {
var product = ProductData.get({
id : item.id
}, function() {
product.name = item.name;
product.description = item.description;
product.ctg_id = item.ctg_id;
product.ctgid = item.ctg_id;
product.$update(item.id);
});
};
$scope.deleteProduct = function(item) {
var product = ProductData.get({
id : item.id
}, function() {
product.id = item.id;
product.$delete(item.id);
});
};
when I was working in WAMP, all methods worked fine.
but when I uploaded to a webserver,
GET request sends the right value example:
http://www.xxx-xxx.com/product/53
but all other methods send this
http://www.xxx-xxx.com/product/53?0=5&1=3
how can I fix this?

You should call: ProductData.delete(...) in the $scope.deleteProduct function

Related

No popup window with AngularJS and typeahead

I have a problem with the typeahead directive. I try to get datas from my datas from my service via $http.get.
In the console output I can see that my datas are coming from the service but I don't get the popup window of the results.
Here is my code:
Html Template:
<input type="text" class="form-control" placeholder="Kundensuche" ng-model="selectedCompany" typeahead="c for c in companies($viewValue)" typeahead-no-results="noResults" typeahead-min-length="3">
Service:
var _search = function (route, id) {
return $http.get(serviceBase + 'api/' + route + '/search/' + id);
};
serviceHelperFactory.search = _search;
Controller:
$scope.companies = function (val) {
var output = [];
var promise = serviceHelper.search('companies', val);
promise.then(function (result) {
result.data.forEach(function (company) {
output.push(company.companyName);
//output.push(company);
});
console.log(output);
}, function (error) {
adminInvoiceService.serviceErrorMessage(error);
});
return output;
}
Thanks!
Ok, I fixed it!
For all with the same problem here is my solution!
$scope.companies = function (val) {
return $http.get('http://localhost:5569/api/companies/search/'+val).then(function (res) {
var companies = [];
console.log(companies);
res.data.forEach(function (item) {
companies.push(item);
});
console.log(companies);
return companies;
});
};

Angular translate inside service

I am struggling with angular translate for my ionic app. The thing is that I have a service with data to share between views but I need to translate this data. Unfortunately I just see blank screen without any errors in console.
I would appreciate if someone could help if there is something wrong with that code (I use useStaticFilesLoader):
app.service('customService', function($q, $rootScope, $filter, $translate) {
$rootScope.$on('$translateChangeSuccess', function () {
var $translate = $filter('translate');
return {
items: [
{
id: '1',
title:$translate('TITLE');
}
]
],
getItems: function() {
return this.items;
},
getItem: function(itemId) {
var dfd = $q.defer();
this.items.forEach(function(item) {
if (item.id === itemId) dfd.resolve(item);
});
return dfd.promise;
}
};
});
});
Try something like this:
app.factory('customService', function($rootScope, $translate) {
var items = [],
updateItems = function() {
items.length = 0;
$translate('TITLE').then(function(title) {
items.push({
id: '1',
title: title;
});
});
};
updateItems();
$rootScope.$on('$translateChangeSuccess', updateItems);
return {
items: items,
getItem: function(itemId) {
var result;
items.forEach(function(item) {
if (item.id === itemId) {
result = item;
}
});
return result;
}
}
});

Uploading images to Firebase with AngularJS

I have a service that handles "episodes": creating, deleting and updating them. It looks like this:
app.service('Episode', ['$firebase', 'FIREBASE_URL', function($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var episodes = $firebase(ref);
return {
all: episodes,
create: function(episode) {
location.reload();
//Add to firebase db
return episodes.$add(episode);
},
delete: function(episodeId) {
location.reload();
return episodes.$remove(episodeId);
},
update: function(episode) {
location.reload();
return episodes.$save(episode);
}
};
}]);
Inside my controller:
app.controller('AdminCtrl', ['$scope', 'Episode', function ($scope, Episode) {
$scope.episodes = Episode.all;
$scope.createEpisode = function(){
Episode.create($scope.episode).then(function(data){
$scope.episode.name = '';
$scope.episode.title = '';
$scope.episode.description = '';
$scope.episode.time = '';
$scope.episode.img = '';
});
};
$scope.deleteEpisode = function(episodeId){
if(confirm('Are you sure you want to delete this episode?') === true) {
Episode.delete(episodeId).then(function(data){
console.log('Episode successfully deleted!');
});
}
};
$scope.updateEpisode = function(episode) {
Episode.update($scope.episode).then(function(data) {
console.log('Episode successfully updated.');
});
};
The only example of uploading images to Firebase from AngularJS I've seen online is this: https://github.com/firebase/firepano
How am I able to incorporate this into an object based addition/update instead of finding it's index/link?

select2 tags with restangular response

How would I pass tags to select2 if the object comes from restfull API using restangular
So I have the following markup
<input type="hidden" ui-select2="select2Options" style="width:100%" ng-model="list_of_string">
returned restangular data
[
{"count":"13","brand":"2DIRECT GMBH"},
{"count":"12","brand":"3M DEUTSCHLAND GMBH"},
{"count":"1","brand":"a-rival"}
]
and here is my Controller method
var filterProducts = function($scope, api) {
api.categories().then(function(response) {
//this is the respose what I would like to use in select2 tags
$scope.brands = response;
});
$scope.list_of_string = ['tag1', 'tag2']
$scope.select2Options = {
'multiple': true,
'simple_tags': true,
'tags': ['tag1', 'tag2', 'tag3', 'tag4'] // Can be empty list.
};
};
Update
Finally I managed
and the hole looks like
$scope.select2Options = {
data: function() {
api.categories().then(function(response) {
$scope.data = response;
});
return {'results': $scope.data};
},
'multiple': true,
formatResult: function(data) {
return data.text;
},
formatSelection: function(data) {
return data.text;
}
}
var filterProducts = function($scope, api) {
api.categories().then(function(response) {
//this is the respose what I would like to use in select2 tags
$scope.brands = response;
$scope.select2Options.tags = response;
});
Hope this will help..

How to manually add a datasource to Angularjs-select2 when select2 is set up as <input/> to load remote data?

I am using the Select2 as a typeahead control. The code below works very well when the user types in the search term.
However, when loading data into the page, I need to be able to manually set the value of the search box.
Ideally something like: $scope.selectedProducerId = {id:1, text:"Existing producer}
However, since no data has been retrieved the Select2 data source is empty.
So what I really need to be able to do is to add a new array of data to the datasource and then set the $scope.selectedProducerId, something like: $scope.producersLookupsSelectOptions.addNewData({id:1, text:"Existing producer}) and then
$scope.selectedProducerId = 1;
Researching this I have seen various suggestions to use initSelection(), but I can't see how to get this to work.
I have also tried to set createSearchChoice(term), but the term is not appearing in the input box.
I would be most grateful for any assistance.
Thanks
This is the html
<div class="col-sm-4">
<input type="text" ui-select2="producersLookupsSelectOptions" ng- model="selectedProducerId" class="form-control" placeholder="[Produtor]" ng-change="selectedProducerIdChanged()"/>
</div>
This is the controller
angular.module("home").controller("TestLookupsCtrl", [
"$scope", "$routeParams", "AddressBookService",
function($scope, $routeParams, AddressBookService) {
$scope.producersLookupsSelectOptions = AddressBookService.producersLookupsSelectOptions();
}
]);
This is the service:
angular.module("addressBook").service("AddressBookService", [
"$http", "$q", function($http, $q) {
var routePrefix = "/api/apiAddressBook/";
//var fetchProducers = function(queryParams) {
// return $http.get(routePrefix + "GetClientsLookup/" + queryParams.data.query).then(queryParams.success);
//};
var _getSelectLookupOptions = function(url, minimumInputLength, idField, textField) {
var _dataSource = [];
var _queryParams;
return {
allowClear: true,
minimumInputLength: minimumInputLength || 3,
ajax: {
data: function(term, page) {
return {
query: term
};
},
quietMillis: 500,
transport: function(queryParams) {
_queryParams = queryParams;
return $http.get(url + queryParams.data.query).success(queryParams.success);
},
results: function(data, page) {
var firstItem = data[0];
if (firstItem) {
if (!firstItem[idField]) {
throw "[id] " + idField + " does not exist in datasource";
}
if (!firstItem[textField]) {
throw "[text] " + textField + " field does not exist in datasource";
}
}
var arr = [];
_.each(data, function(returnedData) {
arr.push({
id: returnedData[idField],
text: returnedData[textField],
data: returnedData
});
});
_dataSource = arr;
return { results: arr };
}
},
dataSource: function() {
return _dataSource;
},
getText: function (id) {
if (_dataSource.length === 0) {
throw ("AddressBookService.getText(): Since the control was not automatically loaded the dataSource has no content");
}
return _.find(_dataSource, { id: id }).text;
}
//initSelection: function(element, callback) {
// callback($(element).data('$ngModelController').$modelValue);
//},
//createSearchChoice:function(term) {
// return term;
//},
addNewData:function(data) {
this.ajax.results(data,1);
};
};
return {
producersLookupsSelectOptions: function() {
var url = routePrefix + "GetClientsLookup/";
return _getSelectLookupOptions(url, 2, "Id", "Name");
},
}
}
]);

Resources