1

Okay, this is a convoluted question and I may be asking for a bad approach. If that's the case, please do let me know.

So I have a directive for a navigation bar. When someone clicks something, I managed to get the directive to add a class and therefore load the bar. Thanks to StackOverflow.

But now, I have a service that gets and sets values. When a value is changed in the service, I want to reflect that in a view. Is such a thing possible?

EDIT For clarification, if I do use a $apply(function()...., how exactly do I do that? My view has something like. My view is not bound to any particular controller, or scope. Not sure if it should be. But here's a snippet of my view:

    <p>
        Are you sure you change that song,
        <br />
  {{ songs[0].title }}
    </p>

Here's my directive:

angular.module('MyApp')
  .directive('navbar', function () {
    return {
      restrict: 'A',
      templateUrl : '/views/partials/nav.html',
      controller: function ($scope, ModalService) {
        $scope.ms = ModalService;
        $scope.songs = {};

        $scope.$watch('ms.songs', function(newVal, oldVal) {
          if(newVal != null) {
            $scope.$apply(function() {
              $scope.songs = newVal;
            });
          }
        });
          },
Community
  • 1
  • 1
Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • If the variable is bound to the controller, can't you $watch for changes from there? – trysis Sep 26 '13 at 13:42
  • I'm almost positive you can't watch values within a service like you're trying to do. Although if it's going to work, you're going to need the third argument for the $watch function, which is "true" for deep-level watching. – Sharondio Sep 26 '13 at 14:44

2 Answers2

1

Have you tried this?

angular.module('MyApp')
  .directive('navbar', function () {
    return {
      restrict: 'A',
      templateUrl : '/views/partials/nav.html',
      controller: function ($scope, ModalService) {
        $scope.songs = ModalService.songs;
      }
  });
jessegavin
  • 74,067
  • 28
  • 136
  • 164
0

I did run into a scenario recently where I had to setup a watch on a service property within a directive and the solution was to setup the watch within the link function similar to:

link: function(scope, element, attrs) {
    // other link code
    scope.$watch(function() { return svc.property; }, function(data) {
        // do something here
    });
    // other link code
}
Mike Pugh
  • 6,787
  • 2
  • 27
  • 25