i try to make a getter and setter for the Supercontainer object, but it dose not seems to work.
PrometeiaECAProModuleMain.factory('ParameterFactory', [function () {
var Supercontainer = function (userId, supercontainerId, bankId) {
this.userId = userId;
this.supercontainerId = supercontainerid;
this.bankId = bankId;
};
return {
setSupercontainerParam: function (userId, supercontainerid, bank) {
supercontainer = new Supercontainer(userId, supercontainerid, bank);
},
getSupercontainerParam: function () {
return supercontainer;
}
};
}]);
I use it like this in my service.js
.factory('CommonService', function ($http, $state, Ls, md5, $filter) {
var headInfo = [];
return {
setData: function (key, data) {
headInfo[key] = data;
},
getData: function (key) {
return headInfo[key];
}
});
In the Controller you would set ur data like this
CommonService.setData('Dataname',{name:bla, price:25});
CommonService.getData('Dataname');
So I can pass all my data from one Controller to another and have it available everywhere
Service example. Can access the functions with ParameterFactory.getSupercontainer();
PrometeiaECAProModuleMain.service('ParameterFactory', function () {
var data = {};
this.setSupercontainer = function (userId, supercontainerId, bankId) {
data = {
'userId': userId,
'supercontainerId': supercontainerId,
'bankId': bankId
};
}
this.getSupercontainer = function () {
return data;
}
});
Related
I'm trying to learn AngularJS and I have the following service that works, but I'm wondering if there's a better way of writing it that is simpler and involves less duplication of code. Can you think of anything?
The service:
app.service("myService", function ($http) {
this.callData1 = function () {
var url = myurl1;
function getData() {
return $http.get(url);
}
return {
getData: getData,
}
},
this.callData2 = function () {
var url = myurl2;
function getData() {
return $http.get(url);
}
return {
getData: getData,
}
},
this.callData3 = function () {
var url = myurl3;
function getData(var1, var2) {
return $http({
url: url,
method: "GET",
params: { var1: var1, var2: var2 }
});
}
return {
getData: getData,
}
}
});
My controller:
app.controller("myController", function ($scope, myService) {
myService.callData1().getData().then(function (response) {
$scope.var1 = response.data;
});
myService.callData2().getData().then(function (response) {
$scope.var2 = response.data;
});
var var1 = "something";
var var2 = "something else";
myService.callData3().getData(var1, var2).then(function (response) {
$scope.var3 = response.data;
});
});
You can generalize it as follows:
app.service("myService", function ($http) {
this.getData = function(url, method, params){
var httpParams = {
url: url,
method: method || "GET", // If method is skipped, use "GET" by default
params: params || {} // If no params are given, take {}
};
return $http.get(httpParams);
};
});
And in controller, you can use this service as follows:
app.controller("myController", function ($scope, myService) {
var url = "https://blahblah";
myService.getData(url).then(function (response) {
$scope.var1 = response.data;
});
var params = {var1: "something", var2: "something2"};
myService.getData(url, "POST", params).then(function (response) {
$scope.var1 = response.data;
});
});
During loading of the partial Html with controller, my function named $scope.actionViewVisitors() is recognized and runs without errors. But whenever I use it inside another function on the same controller, it gives me an error:
TypeError: $scope.actionViewVisitors is not a function. Please see my code below:
angular.module("Visitor.controller", [])
// ============== Controllers
.controller("viewVisitorController", function ($scope, $rootScope, $http, viewVisitorService, viewAccountService, DTOptionsBuilder) {
$scope.visitorList = null;
$scope.viewAccountDetail = null;
$scope.avatar = null;
$scope.visitorDetail = null;
$scope.visitorBtn = "Create";
$scope.actionViewAccount = function () {
$scope.actionViewAccount = viewAccountService.serviceViewAccount()
.then(function (response) {
$scope.viewAccountDetail = response.data.account;
$scope.avatar = "../../avatars/" + response.data.account.AccountId + ".jpg";
})
}
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withDisplayLength(10)
.withOption('bLengthChange', false);
// THIS ONE IS NOT RECOGNIZED
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}
// I DON'T GET ANY ERROR HERE
$scope.actionViewVisitors();
$scope.actionViewAccount();
$scope.createVisitor = function () {
$scope.statusMessage = null;
if ($scope.visitorBtn == "Create") {
$scope.createVisitor = viewVisitorService.serviceCreateVisitor($scope.visitorDetail)
.then(function (response) {
if (response.data.response == '1') {
bootbox.alert({
message: "Successfully created a new visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
} else if (response.data.response == '0') {
bootbox.alert({
message: "Failed in creting visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
}
});
debugger;
$scope.visitorDetail = undefined;
// I GET THE ERROR WHEN I CALL THIS METHOD
$scope.actionViewVisitors();
}
}
})
// ============== Factories
.factory("viewVisitorService", ["$http", function ($http) {
var fac = {};
fac.serviceViewVisitors = function () {
return $http({
url: '/Visitor/ViewVisitors',
method: 'get'
});
}
fac.serviceCreateVisitor = function(visitor) {
return $http({
url: '/Visitor/CreateVisitor',
data: { visitor: visitor },
method: 'post'
});
}
return fac;
}])
You are overwriting the function with Promise in the following line, thus the error is correct
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
Remove $scope.actionViewVisitors =
$scope.actionViewVisitors = function () {
viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
On the first call to the function you are changing it from a function to a Promise. Maybe you want to be returning the result instead?
$scope.actionViewVisitors = function () {
return viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}
In my factory..
var UserService = angular.module('UserService', []);
UserService.factory('UserApi', function ($http) {
var baseUrl = "http://localhost:59844/api";
var UserApi = {};
UserApi.getUsers = function () {
return $http.get(baseUrl + '/UserLogins');
};
});
And in my controller:
var myApp = angular.module('MyApp', ['ngRoute','UserService']);
myApp.controller('HomeController', function ($scope, UserApi) {
getUsers();
function getUsers(){
UserApi.getUsers.success(function (users) {
$scope.users = users;
}).error(function (error) {
$scope.status = "Couldn't load data";
})
}
});
It seems UserApi doesn't return any value. But cannot get it why?
You need to return the service object also
var UserService = angular.module('UserService', []);
UserService.factory('UserApi', function ($http) {
var baseUrl = "http://localhost:59844/api";
var UserApi = {};
UserApi.getUsers = function () {
return $http.get(baseUrl + '/UserLogins');
};
return UserApi;
});
I'm quite new with Angular and I am trying to bring some structure in my website I am building with Angular.
Now I have a Controller where I have some functions which I use on multiple pages. I have heard that I could better make a service out of these functions. How am I able to do this?
This is my Controller in current state:
How can I make a service from $scope.city function and $scope.specials function?
app.controller('DataCtrl', function($scope,$http){
$scope.city = function(){
$scope.items = [];
$http.get('/getdata').then(function(d){
$scope.items = d.data;
$scope.selectedItem = $scope.items[0];
},function(err){
console.log(err);
});
};
/* Function for specialization data */
$scope.specials = function(){
$scope.special = [];
$http.get('/specialdata').then(function(d){
$scope.special = d.data[0];
},function(err){
console.log(err);
});
};
});
Try like this
app.factory('getServiceData', function($http){
return {
getSpecials: function() {
return $http.get("/specialdata")
}
};
});
and for use it in controller inject factory or service into controller as you see in bellow.
app.controller('DataCtrl', function($scope,getServiceData){
getServiceData.getSpecials().then(function(response){
$scope.special = response.data[0];
})
};
Define a service, Here is an example
//Service.js
(function () {
angular.module('myApp')
.service('myService', service);
service.$inject = ['$http']
function service($http) {
this.specialdata = function () {
return $http.get('/specialdata')
}
}
})();
//Controller.js
(function () {
angular.module('myApp')
.controller('DataCtrl', DataCtrl);
DataCtrl.$inject = ['$scope', 'myService']
function DataCtrl($scope, myService) {
/* Function for specialization data */
$scope.specials = function () {
$scope.special = [];
myService.specialdata().then(function (d) {
$scope.special = d.data[0];
}, function (err) {
console.log(err);
});
};
}
})();
It is possible to have a dynamic file resource?
This is my factory
factory('fileResourcedc', function ($resource) {
var FileResourcedc = $resource(
'xml/file.json',{},
{
get:{method:'GET', isArray:false}
}
);
return FileResourcedc;
})
And I am calling it from here:
var deferred = $q.defer();
var successFn = function (result) {
if (angular.equals(result, [])) {
deferred.reject("Failed because empty : " + result.message);
}
else {
deferred.resolve(result);
}
};
var failFn = function (result) {
deferred.reject("Failed dataconfResponse");
};
fileResourcedc.get(successFn, failFn);
return deferred.promise;
Note that in my factory, the filename is hard coded:
'xml/file.json'
What I need is to create a filename parameter and pass it to factory service. Is it possible?
Thaks in advance
This was my solution:
factory('fileResourcedc', function ($resource) {
var FileResourcedc = $resource(
'xml/:myFile',
{},
{
get:{method:'GET', params:{myFile:""}, isArray:false}
}
);
FileResourcedc.prototype.getCatalogue = function (fileName, successCat, failCat) {
return FileResourcedc.get({myFile:fileName}, successCat, failCat);
};
return new FileResourcedc;
})
Call:
var deferred = $q.defer();
var successFn = function (result) {
if (angular.equals(result, {})) {
deferred.reject("No catalogue");
}
else {
deferred.resolve(result);
}
};
var failFn = function (result) {
deferred.reject("Failed catalogue");
};
fileResourcedc.getCatalogue("catalogues.json",successFn, failFn);
return deferred.promise;
Thanks!