i try to share data between two different controllers using a service and watch changes but i don't find how to do this. Here is my code
month-select.component.js:
'use strict'
angular
.module('myApp.monthSelect')
.component('myApp.monthSelect', {
templateUrl: 'monthSelect/month-select.template.html',
controller: 'MonthSelectCtrl',
css: 'monthSelect/month-select.style.css'
})
.controller('MonthSelectCtrl', ['$scope', 'selectedMonthSvc', function ($scope, selectedMonthSvc) {
selectedMonthSvc.setDate($scope.dt)
}])
weeks-list.component.js:
'use strict'
angular
.module('myApp.weeksList')
.component('myApp.weeksList', {
templateUrl: 'weeksList/weeks-list.template.html',
controller: 'WeeksListCtrl',
css: 'weeksList/weeks-list.style.css'
})
.controller('WeeksListCtrl', ['$scope', 'selectedMonthSvc', function ($scope, selectedMonthSvc) {
$scope.getDate = selectedMonthSvc.getDate
}])
get-select-month.service.js
angular.module('myApp.svc', [])
.factory('selectedMonthSvc', function () {
var self = this
var date = ''
self.setDate = function (value) {
return date = value
}
self.getDate = function () {
return date
}
return self
})
It works at init i get the date in my WeeksList controllers, but if i change the date in my MonthSelectCtrl, the value don't update in WeekList.
I'm trying to watch it with $watch but it don't work and have no idea where it goes wrong.
Thank you very much for your help.
1st off change factory to service:
.service('selectedMonthSvc', function () {/**/}
Further
You can write watcher to listen on changes.
So instead:
$scope.getDate = selectedMonthSvc.getDate
try:
$scope.getDate = selectedMonthSvc.getDate;
$scope.$watch('getDate', function() {
// here you get new value
});
This is simple demo that demonstrates your case
When second controller updates date, 1st controller listens and reflects on changes:
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.status = App.getDate();
$scope.$watch(function(){
return App.getDate();
}, function() {
$scope.status = App.getDate();
});
})
.controller('Ctrl2', function ($scope, App) {
$scope.status = App.getDate();
$scope.$watch('status', function() {
App.setDate($scope.status);
});
})
.service('App', function () {
this.data = {};
this.data.date = 'someDate';
var self = this;
var date = ''
self.setDate = function (value) {
this.data.date = value
}
self.getDate = function () {
return this.data.date;
}
});
Try this:
// selectedMonthSvc service:
angular.module('myApp.svc', [])
.factory('selectedMonthSvc', function () {
var date = '';
var self = this
self.setDate = setDate;
self.getDate = getDate;
return self;
function setDate(value) {
date = value;
}
function getDate() {
return date;
}
})
// WeeksListCtrl controller
.controller('WeeksListCtrl', ['$scope', 'selectedMonthSvc', function ($scope, selectedMonthSvc) {
$scope.getDate = getDate;
function getDate() {
return selectedMonthSvc.getDate();
}
}])
var app = angular.module('app', []);
app.controller('firstController', ['$scope','selectedMonthSvc', function($scope, selectedMonthSvc) {
$scope.date = new Date();
$scope.changeDate = function() {
selectedMonthSvc.setDate(new Date())
}
}]);
app.controller('secondController', ['$scope','selectedMonthSvc', function($scope, selectedMonthSvc) {
$scope.date = '';
$scope.selectedMonthSvc = selectedMonthSvc;
$scope.$watch(function() {
return $scope.selectedMonthSvc.getDate();
}, function(newVal) {
$scope.date = newVal;
}, true);
}]);
app.factory('selectedMonthSvc', [function() {
var date = '';
return {
getDate: function () {
return date;
},
setDate: function(d) {
date = d;
}
}
}])
Here is the working plunker https://plnkr.co/edit/w3Y1AyhcGhGCzon8xAsV?p=preview
Related
How can I call $http.get every second to update my page?
var app = angular.module("CompanionApp", []);
app.controller('LoginController', function ($scope, $http) {
$scope.LoginSubmit = function() {
$http.get('/api/player/' + $scope.name)
.then(function(res) {
$scope.connected = res.data.connected;
$scope.health = res.data.health;
$scope.armour = res.data.armour;
})
};
});
Try $interval :
var app = angular.module("CompanionApp", []);
app.controller('LoginController', function ($scope, $http, $interval) {
var interval;
$scope.LoginSubmit = function() {
interval = $interval(function () {
$http.get('/api/player/' + $scope.name)
.then(function(res) {
$scope.connected = res.data.connected;
$scope.health = res.data.health;
$scope.armour = res.data.armour;
})
}, 1000);
};
$scope.stopCalls = function(){ // incase you want to stop the calls using some button click
$interval.cancel(interval);
}
});
I have data in one controller and now I want to share it with another but both controller has different modules. I have used $rootscope but it didn't work. I have used service it also didn't work. link here Service
Is there any other way to do. I have spent one week for this please help me.
toolbar.controler
(function ()
{
'use strict';
angular
.module('app.toolbar')
.controller('ToolbarController', ToolbarController);
function ToolbarController($rootScope, $mdSidenav, msNavFoldService, $translate, $mdToast, $location, $localStorage, $http, $scope)
{
var vm = this;
vm.name = $localStorage.name;
vm.userId = $localStorage._id;
vm.readNotifications = function(notifId){
$http({
url: 'http://192.168.2.8:7200/api/readNotification',
method: 'POST',
data: {notificationId: notifId, userId: vm.userId}
}).then(function(res){
vm.rslt = res.data.result1;
console.log(vm.rslt);
vm.refresh();
$location.path('/sharedwishlistdetails');
}, function(error){
alert(error.data);
})
}
}
})();
The data stored here in vm.reslt.
toolbar.module.js
(function ()
{
'use strict';
angular
.module('app.toolbar', [])
.config(config);
/** #ngInject */
function config($stateProvider, $translatePartialLoaderProvider)
{
$translatePartialLoaderProvider.addPart('app/toolbar');
}
})();
Now I want that result for this controller.
sharedwishlistdetails.controller.js
(function ()
{
'use strict';
angular
.module('app.sharedwishlistdetails')
.controller('SharedWishlistDetailsController', SharedWishlistDetailsController);
/** #ngInject */
//NotificationsController.$inject = ['$http', '$location'];
function SharedWishlistDetailsController($http, $location, $localStorage, $rootScope, $scope)
{
var vm = this;
vm.uid = $localStorage._id;
}
})();
shareddata.service.js
(function ()
{
'use strict';
angular
.module('app.core')
.factory('shareData', shareDataService);
/** #ngInject */
function shareDataService($resource,$http) {
var shareData = {};
return shareData;
}
})();
write a service in 'app.toolbar' module
angular.module('app.toolbar').service('ServiceA', function() {
this.getValue = function() {
return this.myValue;
};
this.setValue = function(newValue) {
this.myValue = newValue;
}
});
In your toolbarController , inject ServiceA and set data -
vm.readNotifications = function(notifId){
$http({
url: 'http://192.168.2.8:7200/api/readNotification',
method: 'POST',
data: {notificationId: notifId, userId: vm.userId}
}).then(function(res){
vm.rslt = res.data.result1;
ServiceA.setValue(vm.rslt);
console.log(vm.rslt);
vm.refresh();
$location.path('/sharedwishlistdetails');
}, function(error){
alert(error.data);
})
}
Now write another service for 'app.sharedwishlistdetails' module -
angular.module('app.sharedwishlistdetails',['app.toolbar']).service('ServiceB', function(ServiceA) {
this.getValue = function() {
return ServiceA.getValue();
};
this.setValue = function() {
ServiceA.setValue('New value');
}
});
Now inject ServiceB in your SharedWishlistDetailsController controller and access data -
var sharedData = ServiceB.getValue();
How could $rootScope failed in your code it would be appreciated if you paste your code: never mind here is an example that will help you out:
All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive.
The rootScope is available in the entire application.If a variable has the same name in both the current scope and in the rootScope, the application use the one in the current scope.
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
});
I have a module with a service defined:
var ngError = angular.module('ngError', []);
ngError.service('ErrorService', ['$scope', function($scope) {
$scope.displayErrors = function(errors) {
alert(errors);
}
}]);
Then I have another module:
var ngLogin = angular.module('ngLogin', ['ngError']);
Which has a controller that attempts to use the first service defined on ngError:
ngLogin.controller('LoginCtrl', ['$scope', 'LoginService', 'ErrorService', function($scope, LoginService, ErrorService) {
$scope.user = {};
$scope.user.id = 0;
$scope.user.token = '';
$scope.login = function(callback) {
LoginService.login($scope.user.username, $scope.user.password, function(token) {
$scope.setToken(token);
$scope.$apply();
if (typeof callback === 'function') {
callback(callback);
}
}, function(errors) {
ErrorService.displayErrors(errors);
});
};
}]);
But some reason this is throwing the following error:
Unknown provider: $scopeProvider <- $scope <- ErrorService
You cannot use $scope within a service. Change the service as follows and it will work:
var ngError = angular.module('ngError', []);
ngError.service('ErrorService', [function() {
this.displayErrors = function(errors) {
alert(errors);
}
}]);
Try like this , working best for me
var app = angular.module('MyApp', []);
app.service('MyService', function () {
var property = 'First';
this.myFunc = function (x) {
return x*5;
}
});
//
controller 2 under second app module
var app = angular.module('AnotherApp',[]);
app.controller("AnotherAppCtrl", function($scope,MyService) {
$scope.value = MyService.myFunc(4);
});
This type of decorator works with services and factories. I expected it to work with providers as well. I've tried the following to decorate ui-router's $stateProvider:
app.config(function($provide) {
$provide.decorator('$state', function ($delegate) {
return $delegate;
});
});
Here's a demo plunk
It should work just the same? See plunk # http://plnkr.co/edit/rSFo1xCoRHjWmrSjJBN1
var app = angular.module('plunker', []);
app.provider('provider', function () {
this.$get = function () {
var provider = {};
var value = 'test';
provider.get = function() {
return value;
}
provider.set = function(param) {
value = param;
}
return provider;
}
});
app.config(function($provide) {
$provide.decorator('provider', function ($delegate) {
$delegate.set('delegate');
return $delegate;
});
});
app.controller('MainCtrl', function($scope, provider) {
$scope.name = provider.get();
});
function ParentCtrl($scope) {
//some function check whether data object in child scope is still null
}
function ChildCtrl($scope) {
$scope.data={};
$scope.func = function(){
$scope.data.x = 1;
};
};
jsFiddle: http://jsfiddle.net/JHwxP/74/
You can use a system of events like you can see here : http://jsfiddle.net/patxy/RAVFM/
If you have 2 controllers with a shared service, you can do it that way :
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
function ControllerZero($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
$scope.$on('handleBroadcast', function() {
$scope.message = sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}
function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'TWO: ' + sharedService.message;
});
}
ControllerZero.$inject = ['$scope', 'mySharedService'];
ControllerOne.$inject = ['$scope', 'mySharedService'];
ControllerTwo.$inject = ['$scope', 'mySharedService'];