I have a device service and a device controller. First, time whenever the controller is called, I invoke setter method to set a boolean value. I want to change that value when the logout function is called which is in different service.
My Device Service
define([], function () {
'use strict';
var DeviceService = [
"AuthService",
function (AuthService) {
var Device_Create = false;
return {
setUserCreatePermission :function () {
if(AuthService.checkForPermission('Device_Create')){
Device_Create = true;
}
},
getUserCreatePermission : function () {
return Device_Create
}
}
}];
return DeviceService;
})
My Device Controller has a init method which calls the setter method in device service. I have set a scope variable. If it set, it will call the method otherwise not.
define([], function () {
'use strict';
var DeviceListCtrl = ["$rootScope", "$scope", "DeviceService",
function ($rootScope, $scope, DeviceService) {
//variables
$scope.deviceList_init = true;
$scope.Device_Create = false;
init();
if(DeviceService.getDeviceCreatePermission()){
$scope.Device_Create = true;
}
function init() {
if($scope.deviceList_init){
DeviceService.setDeviceCreatePermission();
}
$scope.deviceList_init = false;
}
}]
return DeviceListCtrl;
});
Can someone help me ? TIA. I am new to this
I'm not sure I understood your problem but it seems that you are trying to control two different variables to do the same - one in the controller and other in the service.
If you want to have a variable across different controllers, it should be handled in services/factories.
If you want to notify other controllers that a variable has changed somewhere, you can use $rootScope.$broadcast or $scope.$broadcast depending if it is on the scope or not you need.
Related
In this case console logged all properties
app.controller("sgCtrl", function ($scope, $service)
{
var asd=service.getPerson();
console.log(asd);
}
But when im try to get some property its returned me undefined
...console.log(asd.person.Id)
My service
function service($http, $q) {
var service = {
person:[]
};
service.getPerson = function (personId) {
return $http.get('/P/GetP',
{params:{personId:personId}}).success(function (res) {
service.person = res.Person;
});
};
Issue is
1. $http.().success(function() {}) is asynchronous function. So service.person will be available only when control will come inside success callback handler.
2. You have not created service in the correct way.
You can try with below code:
Service code
function service($http, $q) {
this.getPerson = function (personId, successHandler) {
$http.get('/P/GetP',
{params:{personId:personId}}).success(function (res) {
successHandler(res.Person);
});
};
app.service('MyService', service);
Controller Code
app.controller("sgCtrl", function ($scope, MyService) {
function successHandler(person) {
console.log(person.IsActive);
}
MyService.getPerson('somePersonId', successHandler);
}
I believe it will resolve your issues.
Cheers!
I have an AngularJS directive that uses a factory. What I'm trying to achieve is ensuring that when the 'mousedown' event in the directive is triggered, that a function in my factory is then called.
Seems straightforward, however, where I am running into an issue is in the function in the factory. It doesn't have access to any of my variables that were declared in the factory.
Example binding to the mousedown event in my directive -
$element.on('mousedown', factory.onMouseDown);
Example of my factory and the function that is called by my directive -
angular.module('myApp.myFactory', []).factory('myFactory', [, function () {
var myFactory = function () {
this.someVariable = true;
};
myFactory.prototype.onMouseDown = function (e)
{
console.log(this.someVariable); // this.someVariable comes up as 'undefined'
};
return myFactory;
}]);
What do I need to do in order for my function to be able to access variables in my factory?
Thanks!
With the assumption that myFactory is simulating a "class" and the factory variable holds an object instantiated by myFactory there are many approaches to solve it:
(1) Binding an object as context:
$element.on('mousedown', factory.onMouseDown.bind(factory));
(2) Using a closure to preserve the factory reference:
if callback arguments are known:
$element.on('mousedown', function (evt) {
factory.onMouseDown(evt);
});
if callback arguments aren't known:
$element.on('mousedown', function () {
factory.onMouseDown.apply(factory, arguments);
});
(3) Using a constructor function with privileged methods instead of using the prototype property:
angular.module('myApp.myFactory', []).factory('myFactory', function () {
var myFactory = function () {
var self = this;
self.someVariable = true;
self.onMouseDown = function (e) {
console.log(self.someVariable);
};
};
return myFactory;
});
If the function is correctly triggering, what I think you're missing is what is returned by the myFactory factory. The factory and services in angular act like a closure so you can just declare the variable in the factory and have the function return it since it has access to it.
angular.module('myApp.myFactory', []).factory('myFactory', [function () {
var someVariable = "asdkhdsfhkhlskadfhadsflk";
var myFactory = {
mouseDownEvent: function(e){
console.log(someVariable);
}
}
return myFactory;
}]);
I have a angular service function that is being called multiple times.
In the index.html page I have the following line:
<li><i class="pull-right"></i><br/>{{appCtrl.service.getCurrentUser()}} </li>
In the application controller I set the variable
appCtrl.controller('AppController', function ($state, securityService, $log) {
$log.info('App controller');
var appCtrl = this;
appCtrl.service = securityService;
});
In my service I exposed the function
login.factory('securityService', function ($window, $log) {
var currentUser;
return {
setCurrentUser: function (user) {
currentUser = user;
$window.sessionStorage.setItem('User', JSON.stringify(currentUser));
},
getCurrentUser: function () {
$log.info('Calling current user');
if (!currentUser) {
var storedObject = $window.sessionStorage.getItem('User');
currentUser = JSON.parse(storedObject);
}
return currentUser;
}
}
});
The following line in the getCurrentUser function gets called multiple times when the application starts up or page refresh is being done.
$log.info('Calling current user');
The controller is being called only once, I monitor it by looking at $log.info('App controller');
Is it being called as part of the dirty checking process or am I doing something wrong?
Angular calls your function on every digest cycle, you can set breakpoint inside the function and check it. If you are on 1.3 version, then please take a look at One Time Binding feature. If not then call the service inside the controller and bind view to some scope variable:
$scope.currentUser = securityService.getCurrentUser();
And inside view bind to scope variable:
{{currentUser}}
Try this, this is correct factory declaration. Because internally AngularJS calls yout factory like: securityService(injects); , each time you inject (use) your factory.
login.factory('securityService', function ($window, $log) {
var currentUser;
return {
setCurrentUser: function (user) {
currentUser = user;
$window.sessionStorage.setItem('User', JSON.stringify(currentUser));
},
getCurrentUser: function () {
$log.info('Calling current user');
if (!currentUser) {
var storedObject = $window.sessionStorage.getItem('User');
currentUser = JSON.parse(storedObject);
}
return currentUser;
}
};
});
I'm trying to create a provider to handle authentication in my app
function Authenticator($http) {
console.log($http);
return {
test: function() {}
}
}
app.provider('authenticator', function AuthenticatorProvider() {
this.config = function () {
var requestParams;
return {
setRequestParams: function (params) {
requestParams = params;
}
}
}();
this.$get = function($http) {
return new Authenticator($http);
};
});
When i run the code above $http is set as undefined. What am i doing wrong? What's the right way to inject $http service into a custom provider?
Thanks
I am guessing what you really want to be doing is something like this:
app.factory('AuthenticationService', ['$http', function($http) {
var AuthenticationService = function() {};
AuthenticationService.prototype.config = function)() { ... }
return new AuthenticationService();
}]);
This creates a service that can be injected into other controllers, directives and services, which there will only ever be a single shared instance of. Fetching the service by its string means the reference inside the function is local to the closure, which means the variable can be safely renamed, saving precious bandwidth.
I'm having trouble setting $rootScope for Angularjs.
Below is my function
App.controller('Controller',
function (UtilityService, $rootScope) {
var setSession = function () {
$rootScope.test = "yes"; // <-- I get this
UtilityService.getSession().success(
function () {
$rootScope.test = "No"; // <-- I don't get this How do I get/set this value?
});
};
setSession();
});
Additional Info:
One of the ways that might work is to set up a service that is interacted between multiple controllers. Does anybody know how to do this with the service returning an http.get json object.
I'm having trouble getting a dynamic scope in my controller that is instantiated within a service.
In order to address my issue I had to
1) Pass $rootScope into my 2nd controller
App.controller($rootScope) {
2) Set my 2nd controller's function to $rootScope
$rootScope.functionCall = function () {};
3) Set my passed value to $rootScope ($rootScope.orderId)
$rootScope.functionCall = function () {
Service.getItems($rootScope.orderId).success(
function(results) {
$scope.items = results;
});
};
4) within my utility controller, I loop through my results, parsing them, and setting them to $rootScope as you can see in #3 I am initializing "$rootScope.orderId"
angular.forEach(results, function (value, key) {
if (key != null) {
$parse(key).assign($rootScope, value);
}
});
5) I am re-calling the controller's function from within my service call! This is what did the magic for me putting my variable "in scope"
$rootScope.functionCall();
6) I am also testing to see if the function exist cause different pages utilize the utility code but may not have the function to execute
if (typeof $rootScope.functionCall == 'function')
var setSession = function () {
UtilityService.getSession().success(
function (results) {
// Place the rootscope sessions in scope
angular.forEach(results, function (value, key) {
if (key != null) {
$parse(key).assign($rootScope, value);
}
});
// Have to bypass "scope" issues and thus have to execute these fns()
if (typeof $rootScope.functionCall == 'function') {
$rootScope.functionCall();
}
});
};
setSession();
As I wrote before I would use $scope when possible and if you need to share data across multiple controllers you can use a service. The code should be something like:
var app = angular.module('myApp', []);
app.factory('$http', 'myService', function ($http, myService) {
var customers = {};
$http.get("http://www.w3schools.com/website/Customers_JSON.php")
.success(function (response) {
customers = response;
});
return {
customers: customers
};
});
app.controller('controller_one', function($scope, myService) {
$scope.serv = myService.customers;
});
app.controller('controller_two', function($scope, myService) {
$scope.serv = myService.customers;
});