Angularjs watch ng-model change in different controllers

Viewed 533

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.

3 Answers
Related