1

I have a directive that only loads a template like this:

app.directive("sidebar", function(RESOURCE_URL) {
    return {
        templateUrl: RESOURCE_URL + 'sidebar.html'
    };
});

The HTML looks like this:

<sidebar ng-controller="sidebarCtrl" ng-show="ready"></sidebar>

And the controller:

app.controller('sidebarCtrl', function($scope, authService) {
    $scope.service = authService;
    $scope.ready = false;
    $scope.user = {};
    $scope.$watch('service.getUser()', function(value){
        $scope.user = value;
        $scope.ready = true;
    });
});

Is there a way to simply make the directive use the controller's scope variables? Or what's the common method to use in this case?

2
  • You can simply use a service variable to hold the common variable, inject it both in controller and directive.. Commented Nov 1, 2014 at 3:43
  • Directives can have controllers too. Just add controller: 'sidebarCtrl' to your directive, and remove ng-controller="sidebarCtrl" from the HTML. Commented Nov 1, 2014 at 7:31

1 Answer 1

1

There are 2 main ways to access some scope variables inside your directive, the first one is to enable scope inheritance inside of your directive by using scope: true

app.directive("sidebar", function(RESOURCE_URL) {
   return {
       scope: true,
       templateUrl: RESOURCE_URL + 'sidebar.html'
   };
});

which allows you to inherit outer scope inside of your directive, the other way is to attach the controller to your directive by using controller: sideBarCtrl:

app.directive("sidebar", function(RESOURCE_URL) {
  return {
      controller: 'sideBarCtrl',
      templateUrl: RESOURCE_URL + 'sidebar.html'
  };
});

or, you can write a service to hold your scope variables and this will allow you access from different parts of your code to the same instance of the variable.

https://docs.angularjs.org/guide/services

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.