hi all i am using angulrajs
passing one value from one controller
to another controller using service it's work fine but my need is when service value change in controller 2
i get the service value in one scope when scope value change i need trigger the function it's called refresh
function when service
value change and that i need to call the refresh function here my fiddle
Asked
Active
Viewed 288 times
0
3 Answers
3
You can just $watch
your value.storeObject
. Though it's not best of the practices, but it suits this kind of feature.
$scope.$watch('value.storedObject', function(newVal) {
if(newVal !== '') {
refresh()
}
})
working fiddle (open console to see refresh
function logging)

tanmay
- 7,761
- 2
- 19
- 38
-
hi tanmay after page refreshing service value change to null but i need last typed value – jose May 08 '17 at 14:11
-
@jose you can utilize `localStorage` for that inside your refresh or `ng-change` depending on where you want to do it.. it's fairly simple to use.. check out [localStorage docs](https://developer.mozilla.org/en/docs/Web/API/Window/localStorage) – tanmay May 08 '17 at 14:15
-
using localstorage means it'wont delete? – jose May 08 '17 at 14:18
-
@jose it means it will be present on page reload, read docs on how to store and then access it.. it's totally easy to use – tanmay May 08 '17 at 14:20
-
http://stackoverflow.com/questions/43850413/how-to-get-the-value-even-page-reload-in-angularjs @tanmay – jose May 08 '17 at 14:38
1
You can try to use angular default $emit
, $broadcast
, or try to do 2 simple functions in own service
angular.module('app').factory('StoreService', function() {
var listeners = {};
var emit = function(name, val) {
if(listeners[name]) {
listeners[name](val)
}
}
var on = function(name, callback) {
listeners[name] = callback;
}
return {
emit: emit,
on: on,
storedObject: ''
};
});
JSFiddle example
JSFiddle example $watch
JSFiddle example ng-change
is better because, you can use easily debounce

Leguest
- 2,097
- 2
- 17
- 20
-
it's working but when button click then only function trigger my need is when controller 1 value changed automatically refresh function will be call help how to do this – jose May 03 '17 at 05:00
-
I updated my answer. You can attach it on `ng-change` directive or use `$watch` – Leguest May 03 '17 at 05:07
0
you can use broadcast function for that Please check this SO link to find the related answer
How to call a function from another controller in angularjs?
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);

Community
- 1
- 1

Nair Athul
- 823
- 9
- 21
-
i need to work on service @Nair Athul.if possible kindly update my fiddle – jose May 03 '17 at 04:57