I have private values on my Factory service, but when I update a private value in one instance, all instances are updated as well.
Whats the best way to accomplish that without Updating all instances:
angular.module('app').factory('instanceItem', function () {
var _valid = true;
var item = function (id,data){
this.id = id;
this.data = data;
};
item.prototype.setValid = function(bool) {
_valid = bool;
}
item.prototype.getValid = function() {
return _valid
}
return { item:item }
});
What I am getting:
var itemA = new instanceItem.item(1,{});
var itemB = new instanceItem.item(2,{});
itemA.setValid(false);
console.log(itemA.getValid());
//False
console.log(itemB.getValid());
//False
What I am looking for
var itemA = new instanceItem.item(1,{});
var itemB = new instanceItem.item(2,{});
itemA.setValid(false);
console.log(itemA.getValid());
//False
console.log(itemB.getValid());
//True
A service is a singleton. So there is a unique instance of _valid. _valid should be a field of item:
var item = function (id,data){
this.id = id;
this.data = data;
this._valid = true;
};
item.prototype.setValid = function(bool) {
this._valid = bool;
}
item.prototype.getValid = function() {
return this._valid;
}
Or, if you really want to make it private (and also make your service more natural to use):
function createItem(id, data) {
var _valid = true;
return {
id: id,
data: data,
setValid: function(bool) {
_valid = bool;
},
getValid: function() {
return _valid;
}
};
}
return { createItem: createItem }
Related
In Angular 1 my code looked like this:I have 2 dictionaries and functions
var rus = {"hello" : "привет",
"text":"текст",
"home":"дом"};
var eng = {"hello":"hello",
"text":"text",
"home":"home"};
$scope.selectedLang = rus;
translate();
function translate() {
$scope.hello = $scope.selectedLang["hello"];
$scope.text = $scope.selectedLang["text"];
$scope.home = $scope.selectedLang["home"];
}
$scope.switchLang = function(lang) {
if(lang == "rus") {
$scope.selectedLang = rus;
} else {
$scope.selectedLang = eng;
}
translate();
};
But now I need to make this in angular 2. How can I do this?
I have included only class logic here,hope this helps:
export class AppComponent implements OnInit{
public hello:any;
public text:any;
public home:any;
private rus = {
"hello" : "привет",
"text":"текст",
"home":"дом"
};
private eng = {
"hello":"hello",
"text":"text",
"home":"home"
};
private selectedLang:any;
ngOnInit(){
this.selectedLang = this.rus;
this.switchLang('rus'); //calling switchLang() method
}
private selectedLang = this.rus;
translate() {
this.hello = this.selectedLang["hello"];
this.text = this.selectedLang["text"];
this.home = this.selectedLang["home"];
}
switchLang (lang:string){
if(lang == "rus") {
this.selectedLang = this.rus;
} else {
this.selectedLang = this.eng;
}
this.translate();
}
}
So I've been trying to figure this out for a while but it's still stumping me.
Ultimately I want to be able to do the following
object in objects | unique:'DateTime | limitTo:4'//As the year is the first 4 characters
(oh well y10k :))
But I don't know how I'd write that, I'd prefer to have it be inline html code so I don't need to mess around with dependency injection.
Thanks in advance!
Use this derictive:
.filter('unique', function () {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];
var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
});
public Models.ManagedUsersPart GetManagedUsers(int ManagedUsersId)
{
return _cacheManager.Get(ManagedUsersId, ctx =>
{
MonitorManagedUserSignal(ctx, ManagedUsersId);
Timer = new Timer(t => DoUpdate(_contentManager,ManagedUsersId), "c", TimeSpan.FromMinutes(2), TimeSpan.FromMilliseconds(-1));
var managedusers = _contentManager.Get<ManagedUsersPart>(ManagedUsersId);
return managedusers;
});
}
and this is my DoUpdate function:
public void DoUpdate(IContentManager contentmanager,int ManagedUsersId)
{
var transation = _iworkcontext.CreateWorkContextScope().Resolve<ITransactionManager>();
transation.RequireNew();
var manager = getmanager();
var modifiemanageruser = manager.Get<ManagedUsersPart>(ManagedUsersId);
var modi = GetManagedUsers(ManagedUsersId);
modifiemanageruser.InvitedCount = modi.InvitedCount;
}
and ,this is my getmanager function:
public IContentManager getmanager()
{
if (Timermanager == null)
{
Timermanager = _iworkcontext.CreateWorkContextScope().Resolve<IContentManager>();
}
return Timermanager;
}
The question is "modifiemanageruser.InvitedCount = modi.InvitedCount"
this code does not persist update to database,anyone can help?
I create service like this :
export class MDCurrencyService implements IMDCurrencyService {
httpService: ng.IHttpService;
handlerUrl: string;
constructor($http: ng.IHttpService) {
this.httpService = $http;
this.handlerUrl = '/Master/';
}
get(): MDCurrency[]{
var result: MDCurrency[] = [];
var resp: ng.IPromise<any> = this.httpService.get(this.handlerUrl +'GetAllCurrency')
.then((response: any): ng.IPromise<any> => this.handlerResponded(response, null));
resp.then((data) => {
if (data.is_success) {
data.data.forEach(c => {
var converted: MDCurrency = <MDCurrency>c;
converted.selectedCountry = null;
converted.selectedStatus = null;
result.push(converted);
});
return result;
}
else return null;
});
return result;
}
handlerResponded(response: any, params: any): any {
response.data.requestParams = params;
return response.data;
}
}
in my controller :
$scope.currencies = this.currencies = mdCurrencyService.get();
if ($scope.currencies.length > 0) {
console.log('entered'); //never executed
$scope.currencies.forEach(currency => {
for (var ii = 0; ii < this.statuses.length; ii++)
if ($scope.statuses[ii].Id == currency.Status)
currency.selectedStatus = this.statuses[ii];
});
}
but after $scope.currencies filled from service that forEach never executed.
how to execute that code when $scope.currencies is filled by data from service?
mdCurrencyService.get() should be implemented as an asynchronous service returning a promise. It can be utilized this way:
mdCurrencyService.get().then(function (currencies) {
// process result here
$scope.currencies = currencies;
});
I have am Angular Factory that creates global on screen alerts, but unsetting the alerts errors with an
"TypeError: undefined is not a function" error.
My Factory is:
'use strict';
angular.module('meanstackStarterApp')
.factory('Alerts', function ($timeout) {
var alertType = null;
var alertTitle = null;
var alertMessage = null;
return {
setMessage: function(type, title, message, timed) {
console.log("in");
this.alertType = type;
this.alertTitle = title;
this.alertMessage = message;
if (type == "alert-danger")
{
alertMessage = message + alertMessages.alertMessage_GlobalTryAgain;
}
if (timed)
{
// Set Timeout on unset
$timeout(this.unsetMessage(),5000);
}
},
unsetMessage: function() {
console.log("out");
this.alertType = null;
this.alertTitle = null;
this.alertMessage = null;
}
};
});
The setMessage function works fine but the unsetMessage errors on the this.
If I remove this prefix from the variables, the code runs through without erroring, but does not actually set the factory variables.
What am I missing?
I have here something like you, I'm changing your code to look like mine:
angular.module('meanstackStarterApp')
.factory('Alerts', function ($timeout) {
var self = this;
var alertType = null;
var alertTitle = null;
var alertMessage = null;
self.setMessage = function(type, title, message, timed) {
console.log("in");
self.alertType = type;
self.alertTitle = title;
self.alertMessage = message;
if (type == "alert-danger")
{
alertMessage = message + alertMessages.alertMessage_GlobalTryAgain;
}
if (timed)
{
// Set Timeout on unset
$timeout(self.unsetMessage(this),5000);
}
};
self.unsetMessage = function() {
console.log("out");
self.alertType = null;
self.alertTitle = null;
self.alertMessage = null;
};
return self;
});