Shamoon
Shamoon

Reputation: 43609

How can I change information in another view via an AngularJS Directive?

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;
            });
          }
        });
          },

Upvotes: 1

Views: 109

Answers (2)

jessegavin
jessegavin

Reputation: 75690

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;
      }
  });

Upvotes: 1

Mike Pugh
Mike Pugh

Reputation: 6787

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
}

Upvotes: 0

Related Questions