Share value between views in AngularJS - javascript

I have apage with 3 options and each option represent a group of permissions. I have the groupName in my view permissionsConfig but when I edit one group I lose the name of the group and i need the name to make a request to my rest api.
organizationsController.js
app.controller('OrganizationsPermissionsSettingsController',['$rootScope', '$scope', '$modal', 'HelperService', 'AuthService', '$state', '$http', function ($rootScope, $scope, $modal, HelperService, AuthService, $state, $http) {
var controllerScope = $scope;
controllerScope.organizationGroups = [];
$http.get('/api/organization_permissions_groups').success(function (data) {
controllerScope.organizationGroups = data;
});
controllerScope.openOrganizationPermissionsSettings = function (organizationId) {
$state.go('app.organizationPermissionsSettings');
};
var groupId = "";
document.addEventListener("DOMContentLoaded", function(event) {
if(document.getElementById("permissionGroupName").innerHTML!=null){
groupName=document.getElementById("permissionGroupName").innerHTML;
console.log("groupName ",groupName);
$http.get('/api/organization_permissions_groups/getId'+groupName).success(function (data) {
if(data != undefined && data != null){
groupId=data;
console.log("controllerScope.id ",groupId);
}
});
}
});
$scope.navigateToGraphs = function() {
$state.go('app.organizationGraphs', { groupId: groupId });
// then get parameter groupId
$state.params.groupId;
}
$scope.navigateToViews = function() {
$state.go('app.organizationViews', { groupId: groupId });
// then get parameter groupId
$state.params.groupId;
}
}]);
app.controller('OrganizationGraphsController',['$rootScope', '$scope', 'HelperService', '$http', '$stateParams', function ($rootScope, $scope, HelperService, $http, $stateParams) {
var controllerScope = $scope;
controllerScope.graphData = {};
$http.get('/api/organization_permissions_groups/graphs/'+$stateParams.groupId).success(function (data) {
controllerScope.graphData = data.graphs;
});
controllerScope.saveOptions = function () {
$http.put('/api/organization_permissions_groups/graphs/'+$stateParams.groupId, controllerScope.graphData).then(function (response) {
}, function () { });
HelperService.editItem(id, controllerScope.graphData, null, 'Graphs', '/api/organization_permissions_groups/graphs/');
}
$scope.cancel = function () {
$modalInstance.dismiss();
};
}
]);
organizationPermissionsConfigView.html
here I have <td id="permissionGroupName">{{organizationGroup.group_name}}</td> which retrive my permission group name.
I have 3 groups at the moment and with the group name i make a rest api request to get the id and with that id i can make updates on the permission group understand?

Related

Angular: Updating controller scope variable through a factory variable

I looked into examples on how to do this properly but it's definitely not updating on my end. I put a breakpoint to make sure it's updating and going through the timer in the Factory and it's updating properly. I shouldn't have to use $watch right? If someone can help me figure out what's going on it would help with my headache right now lol thanks.
Factory
app.factory('FoundationSystemStatusFactory', ['$timeout', '$q', 'SystemStatusFactory', function ($timeout, $q, SystemStatusFactory) {
var service = {};
service.Count = 0;
service.Ping = 0;
service.PollingTest = function() {
$timeout(function () {
SystemStatusFactory.PingIP('www.google.com')
.then(function (data) {
service.Ping = data.data;
service.Count++;
}, function (data) {
service.Ping = data.data;
});
service.PollingTest();
}, 2000);
}
return service;
}]);
Controller
FoundationSystemStatusFactory.PollingTest();
$scope.ping = FoundationSystemStatusFactory.Ping; //NOT UPDATING
$scope.count = FoundationSystemStatusFactory.Count; //NOT UPDATING
EDIT: tried as Service, still couldn't get it to work:
var self = this;
self.Count = 0;
self.Ping = 0;
self.PollingTest = function () {
$timeout(function () {
SystemStatusFactory.PingIP('www.google.com')
.then(function (data) {
self.Ping = data.data;
self.Count++;
}, function (data) {
self.Ping = data.data;
});
self.PollingTest();
}, 2000);
}
A different approach - events.
app.factory('FoundationSystemStatusFactory', ['$rootScope', '$timeout', '$q', 'SystemStatusFactory', function ($rootScope, $timeout, $q, SystemStatusFactory) {
var service = {
Count: 0
};
service.PollingTest = function() {
$timeout(function () {
SystemStatusFactory.PingIP('www.google.com')
.then(function (data) {
$rootScope.$broadcast('FoundationSystemStatus:ping', data.data);
service.Count++;
}).catch(function (data) {
$rootScope.$broadcast('FoundationSystemStatus:ping', data.data);
});
service.PollingTest();
}, 2000);
}
return service;
}]);
//On controller...
$scope.$on('FoundationSystemStatus:ping', function(ping){
$scope.ping = ping;
});
You can use watcher:
$scope.$watch('FoundationSystemStatusFactory.Ping', function(newValue) {
$scope.ping = newValue;
});
Or you can use reference to factory:
$scope.status = FoundationSystemStatusFactory;
$interval(function() {
console.log($scope.status.Ping); // gets updated
});
Okay I found out how to do it after some more research. Objects are referenced as numbers and strings are not.
Factory
app.factory('FoundationSystemStatusFactory', ['$timeout', '$q', 'SystemStatusFactory', function ($timeout, $q, SystemStatusFactory) {
var service = {};
service.Data = {
Count: 0,
Ping: 0
}
service.PollingTest = function() {
$timeout(function () {
SystemStatusFactory.PingIP('www.google.com')
.then(function (data) {
service.Data.Ping = data.data;
service.Data.Count++;
}, function (data) {
service.Data.Ping = data.data;
});
service.PollingTest();
}, 2000);
}
return service;
}]);
Controller
app.controller('SystemStatusController', ['$scope', '$rootScope', '$timeout', 'FoundationSystemStatusFactory',
function ($scope, $rootScope, $timeout, FoundationSystemStatusFactory) {
FoundationSystemStatusFactory.PollingTest();
$scope.data = FoundationSystemStatusFactory.Data;
}]);
View
{{data.Ping}}
{{data.Count}}

Update the value of variable in one controller from another controller after http.get?

I have two controllers. I want to update a variable from one controller to another controller using service but its not updating.
I want the variable $scope.names in controller 'select' to update in the controller 'current' and display it
app.controller('select', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$http.get('/myapp/stocknames').
success(function(data) {
$scope.names=data;
myService.names=data;
});
}]);
I am using myService to exchange the data between the two controllers. I have declared in my service.
app.service('myService', function($http, $rootScope) {
this.names=[]
});
app.controller('current', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$scope.names=myService.names;
console.log($scope.names);
}]);
Can you please help. How should I make the current controller update the data once the $scope.names variable in the select controller is updated?
According to me what I am doing should work :-/
There are many way to archive this:
First:
By watching for the service variable data change
var app = angular.module('plunker', []);
app.service('dataService', function() {
this.serviceData = "test";
});
app.controller('MainCtrl', function($scope, dataService) {
$scope.mainClickHandler = function(mainData) {
dataService.serviceData = mainData;
}
});
app.controller('SubCtrl', function($scope, dataService) {
$scope.name = 'World';
$scope.getServiceData = function() {
return dataService.serviceData;
}
$scope.$watch("getServiceData()", function(newValue, oldValue) {
if (oldValue != newValue) {
$scope.name = newValue;
}
});
});
http://plnkr.co/edit/G1C81qvDD179NILMMxWb
Second:
Using event broadcast
var app = angular.module('plunker', []);
app.factory('dataService', function($rootScope) {
var serviceData = {
"mydata": "test"
};
$rootScope.$watch(function() {
return serviceData.mydata;
}, function(newValue, oldValue, scope) {
$rootScope.$broadcast('dataService:keyChanged', newValue);
}, true);
return serviceData;
});
app.controller('MainCtrl', function($scope, dataService) {
$scope.mainClickHandler = function(mainData) {
dataService.mydata = mainData;
}
});
app.controller('SubCtrl', function($scope, $rootScope, dataService) {
$scope.name = 'World';
$rootScope.$on('dataService:keyChanged', function currentCityChanged(event, value) {
console.log('data changed', event, value);
$scope.name = value;
});
});
http://plnkr.co/edit/tLsejetcySSyWMukr89u?p=preview
Third:
Using callback
var app = angular.module('plunker', []);
app.service('dataService', function() {
var serviceData = "test";
var callback = null;
this.updateServiceData = function(newData){
serviceData = newData;
if(null!==callback)
{
callback();
}
};
this.getServiceData = function(){
return serviceData;
};
this.regCallback = function(dataCallback){
callback = dataCallback;
};
});
app.controller('MainCtrl', function($scope, dataService) {
$scope.mainClickHandler = function(mainData) {
dataService.updateServiceData(mainData);
}
});
app.controller('SubCtrl', function($scope, dataService) {
$scope.name = 'World';
$scope.dataChangeCalback = function() {
$scope.name = dataService.getServiceData();
}
dataService.regCallback($scope.dataChangeCalback);
});
http://plnkr.co/edit/vrJM1hqD8KwDCf4NkzJX?p=preview
One way to do this is we can bind the entire service to the scope:
myApp.controller('select', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$scope.myService = myService;
$scope.click = function () {
myService.names = "john";
};
And then we change the myService.names directly
current controller should look like this:
myApp.controller('current', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$scope.names=myService.names;
console.log($scope.names);
$scope.$watch(function() { return myService.names; }, function(newVal, oldVal) {
$scope.names = newVal;
});
}]);
}]);
We then use a watcher expression.
or a watcherExpression See for more details.

Send data through a POST request from Angular factory

I have this in the controller
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
$scope.formTodoText = '';
};
});
and this in the factory
angular.module('myApp')
.factory('TaskFactory', function ($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
console.log(1, params);
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log(2);
console.log('data', data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTask: function(taskData) {
console.log('taskData', taskData);
return sendTasks('/task/save', {
taskData : taskData
})
}
}
});
all I need is to know, how to send the data from the controller to the factory in order to do the POST to the specified route ?
You just need to call the function/method inside factory with the required params.
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
TaskFactory.sendTask({data : $scope.formTodoText})
$scope.formTodoText = '';
};
});
You can follow Dan Wahlin blog post.
Controller:
angular.module('customersApp')
.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
dataFactory.updateCustomer(cust)
.success(function () {
$scope.status = 'Updated Customer! Refreshing customer list.';
})
.error(function (error) {
$scope.status = 'Unable to update customer: ' + error.message;
});
}
Factory:
angular.module('customersApp')
.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api/customers';
dataFactory.updateCustomer = function (cust) {
return $http.put(urlBase + '/' + cust.ID, cust)
};
}
Hope that solve your problem.
You can call the function directly on the TaskFactory that you pass into the controller as a dependency.
I've cleaned up your code a bit and created a plunk for you here:
And here's the code:
Controller
(function(angular) {
// Initialise our app
angular.module('myApp', [])
.controller('TaskController', function($scope, TaskFactory) {
// Initialise our variables
$scope.todos = [];
$scope.formTodoText = '';
$scope.addTodo = function() {
// Add an object to our array with a 'text' property
$scope.todos.push({
text: $scope.formTodoText
});
// Clear the input
$scope.formTodoText = '';
// Call function to send all tasks to our endpoint
$scope.sendTodos = function(){
TaskFactory.sendTasks($scope.todos);
}
};
});
})(angular);
Factory
(function(angular) {
angular.module('myApp')
.factory('TaskFactory', function($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log('data: ' + data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTasks: sendTasks
}
});
})(angular);

Angularjs calling factory changes $scope

first of all thank you for your time.
I'm having this issue, and I don't know really well why it is.
main
.controller('MainSelectsCtrl', function($scope, $rootScope, $stateParams, $state, $http, $ionicPopup, $translate, $ionicHistory, Auth, ajax, Data, sections, utils) {
var filterBarInstance;
_initController = function () {
$rootScope.icon_sections = _searchIcon($ionicHistory.currentStateName().split(".")[1])
if (Auth.isLoggedIn()) {
PARENT = $scope.$parent
}
}
...
_initController();
and
main
.controller('MainSelectsCtrl', function($scope, $rootScope, $stateParams, $state, $http, $ionicPopup, $translate, $ionicHistory, Auth, ajax, Data, sections, utils) {
var filterBarInstance;
_initController = function () {
$rootScope.icon_sections = _searchIcon($ionicHistory.currentStateName().split(".")[1])
if ($scope.isLogged) {
PARENT = $scope.$parent
}
}
....
initController();
If I use $scope.isLogged, PARENT is ok and I can access later to a desired method.
If I use Auth.isLoggedIn() I don't know why but $scope.$parent changes.
Here is the factory auth:
angular.module('auth.services', [])
.factory('Auth', function () {
var _user = JSON.parse(window.localStorage['session']);
var setUser = function (session) {
_user = session;
window.localStorage['session'] = JSON.stringify(_user);
}
return {
setUser: setUser,
isLoggedIn: function () {
return _user ? true : false;
},
getUser: function () {
return _user;
},
logout: function () {
window.localStorage.removeItem("session");
_user = null;
}
}
});
Thank you very much

Dynamic injection angularjs?

i am using one of the basic concept of angularjs that child controller inherit from parent controller. so i have writen the following code :
var editChannelCtrl = function ($scope, $route, $location, youtube) {
$scope.loading = false;
$scope.saved = false;
$scope.errors = [];
if (angular.isDefined($route.current.params.id)) {
$scope.isOldChannel = true;
$scope.isNewChannel = false;
} else {
$scope.isNewChannel = true;
$scope.isOldChannel = false;
}
};
editChannelCtrl.$inject = ['$scope', '$route', '$location', 'youtube'];
editChannelCtrl.resolve = {
channel: ['ServiceChannel' , function (ServiceChannel) {
return ServiceChannel.ChannelLoader();
}]
};
var oldChannelCtrl = function ($scope, $location, channel) {
$scope.channel = channel;
};
oldChannelCtrl.$inject = ['$scope' , '$location', 'channel'];
var newChannelCtrl = function ($scope, $location, Channel) {
$scope.channel = {
id: null,
version: 1
};
};
newChannelCtrl.$inject = ['$scope' , '$location', 'Channel'];
and for routes what i do , that i resolve the channel that load the channel for the edit form with the following code.
.when('/admin/refactor/channel/edit/:id', {
controller: editChannelCtrl,
templateUrl: '/admin/assets/views/channelForm.html',
resolve: editChannelCtrl.resolve
})
.when('/admin/refactor/channel/new', {
controller: editChannelCtrl,
templateUrl: '/admin/assets/views/channelForm.html'
})
but i don't know why angularjs don't figure how to inject channel to oldChannelCtrl ?

Categories

Resources