I have the following JSFiddle
I want two way binding for these sliders that will eventually set the value in the service
Meaning that the on is changed also the second and the value in the service also
HTML:
<div>
<div ng-controller="FirstCtrl">
<input type="range" ng-model="speakerVolume" />
{{speakerVolume}}
</div>
<div ng-controller="SecondCtrl">
<input type="range" ng-model="speakerVolume" />
{{speakerVolume}}
</div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.controller('FirstCtrl', function($scope, voipService) {
$scope.speakerVolume = voipService.speakerVolume;
$scope.$watch("speakerVolume", function (newValue) {
voipService.speakerVolume = newValue;
voipService.setVolume(newValue);
});
});
myApp.controller('SecondCtrl', function($scope, voipService) {
$scope.speakerVolume = voipService.speakerVolume;
$scope.$watch("speakerVolume", function (newValue) {
$scope.speakerVolume = newValue;
voipService.setVolume(newValue);
});
});
myApp.service('voipService', function() {
this.speakerVolume = 50;
this.setVolume = function(newVal){
self.speakerVolume = newVal;
}
});
Final Answer in Fiddle:
Fiddle - Final Answer
one way is to watch also service value, not just scope variable
var myApp = angular.module('myApp', []);
myApp.controller('FirstCtrl', function($scope, voipService) {
$scope.speakerVolume = voipService.speakerVolume;
$scope.$watch("speakerVolume", function (newValue) {
voipService.speakerVolume = newValue;
});
$scope.$watch(function() {
return voipService.speakerVolume;
}, function (newValue) {
$scope.speakerVolume = newValue;
});
});
myApp.controller('SecondCtrl', function($scope, voipService) {
$scope.speakerVolume = voipService.speakerVolume;
$scope.$watch("speakerVolume", function (newValue) {
voipService.setVolume(newValue);
});
$scope.$watch(function(){
return voipService.speakerVolume;
}, function (newValue) {
$scope.speakerVolume = newValue;
});
});
myApp.service('voipService', function() {
var self = this;
this.speakerVolume = 50;
this.setVolume = function(newVal){
self.speakerVolume = newVal;
}
});
second way is to use $broadcast in the service (when the value is changed) and update values in all controllers when this custom event is fired
Related
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
I have a view for SidebarController like below -
<a ng-click="reachMe($event);$event.preventDefault()" ng-href="#/app/hello">
Before going to the link I want to call reachMe() to check some changes on page and need to show an alert if any changes made
function SidebarController($rootScope, $scope, $state, $location, SidebarLoader){
$scope.reachMe = function(event){
//here I want to call function isPageChanged() from StaticPageController
//something like this
// if StaticPageController.isPageChanged() return true
// then show alert
// else
// $location.url($href)
}
}
Update 1 :
Not sure about this, But give it a try.
<div ng-app="testApp" ng-controller="ControllerOne">
<button ng-click="methodA();"> Call Another Controller</button>
</div>
<script>
var app = angular.module('testApp', []);
app.controller('ControllerOne', function($scope, $rootScope) {
$scope.reachMe = function() {
var arrayData = [1,2,3];
$rootScope.$emit('callEvent', arrayData);
if($rootScope.isChanged){
// Show Alert
}else{
//Go to route
}
}
});
app.controller('ControllerTwo', function($scope, $rootScope,$state) {
$scope.checkSomethingChanged = function() {
alert("Hello");
$rootScope.isChanged = true;
}
$rootScope.$on('callEvent', function(event, data) {
console.log(data);
$scope.checkSomethingChanged();
});
});
Following method worked for me perfectly :
<div ng-app="testApp" ng-controller="ControllerOne">
<button ng-click="methodA();"> Call Another Controller</button>
</div>
<script>
var app = angular.module('testApp', []);
app.controller('ControllerOne', function($scope, $rootScope) {
$scope.methodA = function() {
var arrayData = [1,2,3];
$rootScope.$emit('callEvent', arrayData);
}
});
app.controller('ControllerTwo', function($scope, $rootScope) {
$scope.reachMe = function() {
alert("Hello");
}
$rootScope.$on('callEvent', function(event, data) {
console.log(data);
$scope.reachMe();
});
});
</script>
A controller is not the right concept for sharing functionality. Use a Factory or Service for that.
var logicFactory = function () {
return {
methodA: function () {
},
methodB: function()
{
}
};
}
You can then inject that factory into each controller where it is needed like:
var ControllerA = function ($scope,logicFactory) {
$scope.logic = logicFactory;
}
ControllerA.$inject = ['$scope', 'logicFactory'];
Another option is to use the broadcast/emit Patern. But I would use that only where really necessary:
Usage of $broadcast(), $emit() And $on() in AngularJS
/*service */
app.service('sharedProperties', function () {
var property = 'First';
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
/*first contoller */
app.controller('loginCtrl',function($scope,$location,$http,$window,sharedProperties){
$scope.submit =function(){
var username=$scope.username;
var pass=$scope.password;
sharedProperties.setProperty(username);
$location.path('/userdashboard');
$window.location.reload();
});
}
});
/*second controller*/
app.controller('empController', function($route,$scope,$http,$routeParams,sharedProperties){
$scope.getEmployees = function(){
alert( sharedProperties.getProperty());
};
};
Try this, it will work for you. :
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="sendData();"></button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
function sendData($scope) {
var arrayData = [1,2,3];
$scope.$emit('someEvent', arrayData);
}
});
app.controller('yourCtrl', function($scope, $http) {
$scope.$on('someEvent', function(event, data) {
console.log(data);
});
});
</script>
Service does not need to return anything. You have to assign everything in this variable. Because service will create instance by default and use that as a base object.
app.service('sharedProperties', function () {
this.property = 'First';
});
Then in controller
sharedProperties.property = $scope.username;
Had you been looking to use factory
app.factory('sharedProperties', function () {
var factory = {};
factory.property = 'Hello';
factory.setProperty = function (value) {
factory.property = value;
};
return factory;
});
Then in controller you would use it
sharedProperties.setProperty($scope.username); // Setter
$scope.var = sharedProperties.property; //getter
EDIT
Working Plnkr
You can assign members to $rootScope, which will store data globally for your app. Just inject $rootScope to each controller.
For instance...
/*first controller */
app.controller('loginCtrl',function($scope,$rootScope,$location,$http,$window,sharedProperties){
$scope.submit =function(){
var username=$scope.username;
var pass=$scope.password;
$rootScope.username = username;
$location.path('/userdashboard');
$window.location.reload();
});
}
});
This will make 'username' available to any controller that injects and consumes $rootScope.
/*second controller*/
app.controller('empController', function($route,$scope,$rootScope,$http,$routeParams,sharedProperties){
$scope.getEmployees = function(){
alert($rootScope.username);
};
};
Ok i know that isn't a good practice to put a watcher inside a controller, but in this case how can i avoid to use watcher?
ps: $rootscope it's not a option ok?
here is the code:
plunker
Edit - here what i did:
plunker
And here is the js code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, mainService) {
var flag = false;
$scope.btn = function () {
flag = !flag;
mainService.setData(flag);
}
});
app.controller('DemoOneCtrl', function($scope, mainService) {
$scope.name = 'World';
$scope.mainService = mainService;
$scope.show = false;
$scope.$watch('mainService.getData()', function (data) {
$scope.show = data;
});
});
app.service('mainService', function () {
var data = false;
this.setData = function (str) {
data = str;
};
this.getData = function () {
return data;
};
});
And html:
<div ng-controller="MainCtrl">
<button ng-click="btn()">GO!</button>
</div>
<div ng-controller="DemoOneCtrl">
<p ng-show="show">Hello World</p>
</div>
One way to do it is to bind your ng-show to a service function.
app.controller('MainCtrl', function($scope, mainService) {
var flag = false;
$scope.btn = function () {
flag = !flag;
mainService.setData(flag);
}
});
app.controller('DemoOneCtrl', function($scope, mainService) {
$scope.name = 'World';
$scope.mainService = mainService;
$scope.show = mainService.getData;
});
app.service('mainService', function () {
var data = false;
this.setData = function (str) {
data = str;
};
this.getData = function () {
return data;
};
});
Notice how $scope.show is set to mainService.getData. Now you can bind show() to ng-show.
<p ng-show="show()">Hello World</p>
No $watch needed.
Demo
I'm trying to watch for changes in a service from a controller. I tried various things based on many qns here on stackoverflow, but I've been unable to make it work.
html:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-click="setFTag()">Click Me</div>
</div>
</div>
javascript:
var myApp = angular.module('myApp',[]);
myApp.service('myService', function() {
this.tags = {
a: true,
b: true
};
this.setFalseTag = function() {
alert("Within myService->setFalseTag");
this.tags.a = false;
this.tags.b = false;
//how do I get the watch in MyCtrl to be triggered?
};
});
myApp.controller('MyCtrl', function($scope, myService) {
$scope.setFTag = function() {
alert("Within MyCtrl->setFTag");
myService.setFalseTag();
};
$scope.$watch(myService.tags, function(newVal, oldVal) {
alert("Inside watch");
console.log(newVal);
console.log(oldVal);
}, true);
});
How do I get the watch to trigger in the Controller?
jsfiddle
Try to write $watch by this way:
myApp.controller('MyCtrl', function($scope, myService) {
$scope.setFTag = function() {
myService.setFalseTag();
};
$scope.$watch(function () {
return myService.tags;
},
function(newVal, oldVal) {
/*...*/
}, true);
});
Demo Fiddle
[EDIT]
Sometimes this way will not work especially if service has been updated from 3d party.
To make it work we must help to angular to fire digest cycle.
Here is an example:
On service side when we want update tags value write something like:
if($rootScope.$root.$$phase != '$apply' && $rootScope.$root.$$phase != '$digest'){
$rootScope.$apply(function() {
self.tags = true;
});
}
else {
self.tags = true;
}