Tamás Pap
Tamás Pap

Reputation: 18273

Isolated scope for directives

I'm having some troubles understanding isolated scopes in Angular directives. I've read the official documentation, watched a lot of videos about the subject, so now I'm know what's the purpose of them, but I'm not sure how to use them.

Here is a simple example.
I created a directive called searchBox (see full source and demo)

var myApp = angular.module('myApp', []);

myApp.directive('searchBox', function($timeout) {
  return {
    restrict: 'A',
    scope: true,
    link: function(scope, element) {                
      scope.open = false;

      // Show search input
      scope.showInput = function() {
        scope.open = true;

        // Focus the input
        $timeout(function() {
          element.find('input').focus();
        }, 0);
      };

      // Hide search input
      scope.hideInput = function() {
        scope.open = false;
      };
    }
  }
});

and this actually works as expected. However, I want to isolate the scope of the directive, but if I change scope: true to scope: {} (see full source and demo)) it no longer works, but I can't see any errors in the console.

I'm sure it's something elementary I'm doing wrong, but I really hope somebody can open my eyes and help me understand this.

Upvotes: 3

Views: 327

Answers (1)

rvignacio
rvignacio

Reputation: 1740

Got it working.

The problem was that the directive should include it's own template (or have the transclude option set to true) because you are wrapping other elements.

If other directives (like ng-click or ng-blur) are defined inside a template in the search-box directive, they get evaluated against the search-box $scope. But if there isn't a template, they bubble up to the parent $scope (which, in this case, doesn't have the functions showInput() or hideInput(), etc).

If you don't want to have the html string in the directive's declaration, you can use the templateUrl option to reference external templates.

Upvotes: 5

Related Questions