Skip to content

Instantly share code, notes, and snippets.

@ronsuez
Last active January 8, 2017 01:24
Show Gist options
  • Save ronsuez/173f3424ce1a7be919a90fd729e9c4b4 to your computer and use it in GitHub Desktop.
Save ronsuez/173f3424ce1a7be919a90fd729e9c4b4 to your computer and use it in GitHub Desktop.
watching.service.variables.js
//Service
(function() {
'use strict';
angular
.module('module')
.factory('myService', factory);
factory.$inject = ['$http', '$q'];
/* @ngInject */
function factory(dependencies) {
var service = {
data: [],
getData: getData
};
return service;
function getData(params) {
var deferred = $q.defer();
$http.get('/url/', {
params: params
})
.success(function(res) {
deferred.resolve(res);
angular.copy(res, service.data); //aqui se copia a la variable del servicio y el watch en child controller deberia actualizarce
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
}
}
})();
///Parent Controller
(function() {
'use strict';
angular
.module('module')
.controller('ParentController', Controller);
Controller.$inject = ['myService'];
/* @ngInject */
function Controller(myService) {
var vm = this;
activate();
function activate() {
console.log('Parent Controller');
}
$scope.getData = function(params) {
myService.getData(params);
}
}
})();
//Child Controller
(function() {
'use strict';
angular
.module('module')
.controller('ChildController', Controller);
Controller.$inject = ['$scope', 'myService'];
/* @ngInject */
function Controller($scope, myService) {
var vm = this;
$scope.data = myService.data; //esta variable se actualizara cuando myService.data se actualice, es como magia!!!
activate();
function activate() {
console.log('Child controller');
}
$scope.$watch('data', function(current, original) {
if (!current.length) return;
console.log(current);
})
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment