This is the function I made:
var _loadNieuws =
function (url) {
switch (url) {
case 'example1':
_nieuws = EXAMPLE1_NIEUWS;
break;
case 'example2':
_nieuws = EXAMPLE2_NIEUWS;
break;
}
}
Now I'm trying to give the url a value using my controller, this is how far I came: NieuwsService.loadNieuws.url = 'example1';
But then I get this error:
"Cannot set property 'url' of undefined".
This is my whole factory:
App.factory('NieuwsService', ['EXAMPLE1_NIEUWS', 'EXAMPLE2_NIEUWS', function (EXAMPLE1_NIEUWS, EXAMPLE2_NIEUWS) {
var nieuwsService = {};
var _nieuws = [];
var _loadNieuws =
function (url) {
switch (url) {
case 'example1':
_nieuws = EXAMPLE1_NIEUWS;
break;
case 'example2':
_nieuws = EXAMPLE2_NIEUWS;
break;
}
}
nieuwsService.loadNiews = _loadNieuws;
nieuwsService.nieuws = _nieuws;
return nieuwsService;
}]);
So my question is how do I give the property url in the function a value using my controller ?
Where is the question?
If you want to pass variable into the function put it as a parameter in function:
<div ng-click="_loadNieuws(loadNieuws.url)">Click here</div>
and your js-code will work fine
I think you need something like this in your controller :
$scope.url = NieuwsService.loadNieuws('example1');
This is the solution that worked fine for me:
var url = 'example1';
$scope.url = angular.copy(NieuwsService.loadNieuws(url));
Related
The issue I'm having is that I'm trying to get data from my factory to my controller in time for the controller to access that data. Currently, when I console log out the data, I get an empty object, but if I examine the data further I get the whole "value was snapshotted, but here it is live" in Chrome.
Here's my Factory, called DataService:
var data = {};
var firstPillarData = {};
var secondPillarData = {};
var thirdPillarData = {};
firstPillarData.ourArray = [];
secondPillarData.ourArray = [];
thirdPillarData.ourArray = [];
function userRetrievalSuccess(response){
console.log('userRetrievalSuccess', response.data);
data.users = response.data;
console.log('data.users is', data.users);
console.log('and the data object is', data);
for(var i = 0; i < data.users.length; i++){
if(data.users[i].initiatives != null){
console.log("we have initiatives for this user", data.users[i]);
for(var j = 0; j < data.users[i].initiatives.length; j++){
switch(data.users[i].initiatives[j].pillar){
case 1:
firstPillarData.ourArray.push(data.users[i].initiatives[j]);
break;
case 2:
secondPillarData.ourArray.push(data.users[i].initiatives[j]);
break;
case 3:
thirdPillarData.ourArray.push(data.users[i].initiatives[j]);
break;
default:
break;
}
}
}
}
data.firstPillarData = firstPillarData;
data.secondPillarData = secondPillarData;
data.thirdPillarData = thirdPillarData;
console.log("our data.firstPillarData is", data.firstPillarData);
console.log("our data.secondPillarData is", data.secondPillarData);
console.log("our data.thirdPillarData is", data.thirdPillarData);
return data;
}
function userRetrievalFail(){
console.log('error retrieving users');
}
function getAllUserData(){
$http.get('/kpi/allUsers/').then(userRetrievalSuccess, userRetrievalFail)
}
And here's where it's being called in my controller:
DataService.getAllUserData();
var data = DataService.data;
I thought that using the .then method on the $http.get would handle my issue, but it clearly isn't. What am I doing wrong?
It turns out that adding a second promise/.then on the controller side took care of my issues. But thanks to #JB-Nizet and #Ladmerc for the help!
I am writing a client that needs to access resource restparameter through three different paths. The paths are resource/:resourceId/restparameter, restparameter/:restparameterId/restparameter and restmethod/:restmethodId/restparamter. I have tried to do this by using $location but it doesn't work. For example when I try to access the restparameter through the path:http://localhost:8085/output/#/restmethod/54/restparameter the client calls only this: GET http://localhost:8085/WSAT/multirestparameterManager/restparameter/restparameter, which obviously responses 404 Not Found. I'm guessing that it doesn't go in the matching if, since it doesn't even try to call GET http://localhost:8085/WSAT/multirestparameterManager/restmethod/restparameter My controller is this:
WSAT.controller('restparameterCtrl',['$scope','$resource','$location','$route','$routeParams','popupService', 'restparameterFactory',
function($scope,$resource, $location, $route,$routeParams,popupService, restparameterFactory, $window)
{ $scope.$location = {};
var result = $location.url();
if(result.includes("restparameter")){var Restparameter = $resource('http://localhost\\:8085/WSAT/multirestparameterManager/restparameter/:restparameterId/restparameter/');
$scope.restparameters = Restparameter.get({restparameterId: $routeParams.restparameterId});}
else if(result.includes("resource")){var Restparameter = $resource('http://localhost\\:8085/WSAT/multirestparameterManager/resource/:resourceId/restparameter/');
$scope.restparameters = Restparameter.get({resourceId: $routeParams.resourceId});}
else if(result.includes("restmethod")){var Restparameter = $resource('http://localhost\\:8085/WSAT/multirestparameterManager/restmethod/:restmethodId/restparameter/');
$scope.restparameters = Restparameter.get({restmethodId: $routeParams.restmethodId});}
You are not passing paramDefaults while creating $resourceobject.
If you want :restparameterId parameter should get from passed object,then you should tell the angular by passing the default parameter {restparameterId:'#id'}.
And the same for other.
Check $ngResource for more.
if (result.includes("restparameter")) {
var Restparameter = $resource('multirestparameterManager/restparameter/:restparameterId/restparameter/',{restparameterId:'#id'});
$scope.restparameters = Restparameter.get({ restparameterId: $routeParams.restparameterId });
} else if (result.includes("resource")) {
var Restparameter = $resource('multirestparameterManager/resource/:resourceId/restparameter/',{resourceId:'#id'});
$scope.restparameters = Restparameter.get({ resourceId: $routeParams.resourceId });
} else if (result.includes("restmethod")) {
var Restparameter = $resource('multirestparameterManager/restmethod/:restmethodId/restparameter/',{restmethodId:'#id'});
$scope.restparameters = Restparameter.get({ restmethodId: $routeParams.restmethodId });
}
You need to pass parameters while using $resource object.
var URL = 'http://localhost\\:8085/';
var Restparameter = $resource(URL +"WSAT/multirestparameterManager/:masterpath/:Id/restparameter/", "{Id:'#Id'}", {
});
if (result.includes("restparameter")) {
$scope.restparameters = Restparameter.get({ Id: $routeParams.restparameterId });
} else if (result.includes("resource")) {
$scope.restparameters = Restparameter.get({ Id: $routeParams.resourceId });
} else if (result.includes("restmethod")) {
$scope.restparameters = Restparameter.get({ Id: $routeParams.restmethodId });
}
I have a service:
storeApp.service('currentCustomer',function($http) {
this.customerID = 0;
this.customerInfo = {}
this.customerAttributes = {}
this.getCustomerInfo = function () {
if (this.customerID != 0) {
$http.get('/customers/' + this.customerID).
then(function (result) {
this.customerInfo = result.data[0]
})
}
}
and a controller:
storeApp.controller('storeList',function($scope,$http,currentCustomer) {
$scope.changeCust = function changeCust(id) {
currentCustomer.customerID = id;
currentCustomer.getCustomerInfo()
console.log("After Change customer:")
console.log(currentCustomer)
}
$scope.selectedStore = currentCustomer
});
If I try to access selectedStore.customerID, I get values.
If I try to access selectedStore.customerInfo, I get an empty array, even though when i put console logging in to check the values, it says they are assigned.
Any ideas what I'm doing wrong? Thanks everyone.
You are manually assigning a value to CustomerId, and your service method is assigning a value to customerInfo. Except this in the service method, is not the same as this in the service. You should instantiate a var self = this; reference inside the service and use this value in all your object manipulation. eg: self.customerInfo = ....
Your reference for this has been changed inside function. first store this reference in some variable and then assign properties, some prefer to use the word self but I prefer service
storeApp.service('currentCustomer',function($http) {
var service = this;
service.customerID = 0;
service.customerInfo = {}
service.customerAttributes = {}
service.getCustomerInfo = function () {
if (service.customerID != 0) {
$http.get('/customers/' + this.customerID).
then(function (result) {
service.customerInfo = result.data[0]
});
}
}
I'm trying to construct a translated message by looping over an array of objects and then adding a new "message" property to that object containing the translated string. I see the correct message output while inside $translate.then(); but when I assign the message to the object it is undefined. What is the correct way to resolve the promise returned from $translate.then() and assign it to the "message" property?
//items.controller.js
function getItems() {
return itemsFactory.getItems()
.then(function (response) {
vm.items = initItemsList(response.activities);
});
}
function initItemsList(itemsList) {
for (var i = 0; i < itemsList.length; i++){
var activityType = itemsList[i].activityType;
switch (activityType){
case "HISTORY": {
var itemName = itemsList[i].item.itemName;
var itemVersion = itemsList[i].item.itemVersion;
$translate('activity.'+activityType, { itemname: itemName, itemversion: itemVersion }).then(function(content){
vm.itemContent = content;
console.log(vm.itemContent); // correct message displayed.
});
break;
}
default: {
break;
}
}
itemsList[i].message = vm.itemContent; // undefined
}
return itemsList;
}
// translation.json
"activity : {
"HISTORY" : "History for {{ itemname }} {{ itemversion }}."
}
Promises are always resolved asynchronously. So the statement
itemsList[i].message = vm.itemContent;
, which is executed right after the switch, is executed before the callback passed to the $translate promise. Just move the statement to the callback:
$translate('activity.'+activityType, { itemname: itemName, itemversion: itemVersion }).then(function(content){
vm.itemContent = content;
console.log(vm.itemContent);
itemsList[i].message = vm.itemContent;
});
As #Vegar correctly states, the code inside then is executed after the assignment so moving the assignment inside then function will take care of the problem. However, your itemsList will be returned from the function before all the translations are done so you will need to return a promise that resolves when all translations are done:
function initItemsList(itemsList) {
var allTranslations = [];
for (var i = 0; i < itemsList.length; i++){
var activityType = itemsList[i].activityType;
switch (activityType){
case "HISTORY": {
var itemName = itemsList[i].item.itemName;
var itemVersion = itemsList[i].item.itemVersion;
allTranslations.push($translate('activity.'+activityType, { itemname: itemName, itemversion: itemVersion }).then(function(content){
vm.itemContent = content;
itemsList[i].message = vm.itemContent;
}));
break;
}
default: {
break;
}
}
}
return $q.all(allTranslations);
}
The caller of your function will have to do like:
initItemList(itemList).then(function(translatedList){
//Do stuff with translated list
});
Hi I am trying to update my data in angularJS(frontend) and laravel(backend).
But even I got an data from id, but I always make a new data.
I thought it cause my laravel code's fault, but not sure.
AngularJS service
app.factory('Assets', function($resource) {
return $resource('/api/assets/:assetId',{assetId:'#id'},{
update: {
method: 'PUT' // this method issues a PUT request
}
});
});
Controller (for data list)
app.controller('fixedAssetListCtrl',['$scope','$location','$rootScope','Assets', function($scope, $location, $rootScope,Assets){
$scope.assets = Assets.query();
$scope.goEdit = function(id){
Assets.query({assetId:id}.edit);
$location.path('/editFixedAsset').search({assetId:id});
}
}]);
Controller (for edit)
app.controller('fixedAssetEditCtrl',['$scope','$location','$rootScope','Assets',
function($scope, $location, $rootScope, Assets){
var edit_id=$location.path('/editFixedAsset').search();
var assetId=parseInt(edit_id.assetId);
//window.alert($rootScope.assetId.ID);
$scope.editassets = Assets.query({assetId});// getting data
// console.log($scope.editassets);
$scope.asset = {};
$scope.updateFixedAsset =function(asset){
var faData ={
detailAssetCode:$scope.detailAssetCode,
detailDescription:$scope.detailDescription,
detailParchaseDate:$scope.detailParchaseDate,
detailSoldDate:$scope.detailSoldDate
} //end of faData
Assets.update({assetId},asset);
}
}]);
Laravel Routes
Route::group(array('prefix' => '/api'), function () {
Route::resource('assets', 'AssetController');
});
Controller
public function show($id){
$assets = FAModel::find($id);
$response[] = [
'detailAssetCode' => $assets->AssetCode,
'detailDescription' => $assets->Description,
'detailPurchaseDate' => $assets->PurchaseDate,
'detailoldDate' =>$assets->SoldDate,
];
return Response::json($response, 200);
}
public function update($id){
$FAModelObj = new FAModel;
$fixedAssetData = FAModel::find($id);
$FAModelObj->AssetCode = Input::json('detailAssetCode');
$FAModelObj->Description = Input::json('detailDescription');//need to be JSON object??
$FAModelObj->PurchaseDate = Input::json('detailPurchaseDate');
$FAModelObj->SoldDate = Input::json('detailSoldDate');
$FAModelObj->push();
return Response::json(array('success'=>true));
}
Can you find the problem??
How can I change to update the data? Thanks.
The problem is that you create a new instance to save data instead of existing one. That's why new row is created in database. Your code should be like that.
public function update($id){
$fixedAssetData = FAModel::find($id);
$fixedAssetData->AssetCode = Input::json('detailAssetCode');
$fixedAssetData->Description = Input::json('detailDescription');//need to be JSON object??
$fixedAssetData->PurchaseDate = Input::json('detailPurchaseDate');
$fixedAssetData->SoldDate = Input::json('detailSoldDate');
$fixedAssetData->push();
return Response::json(array('success'=>true));
}
Hope it will be useful for you.