3

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.

1 Answer 1

5

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.

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

1 Comment

Nice catch. Slight correction though: if you don't specify the template for the directive, other directives (ng-click, ng-blur) get bubbled up to the parent's scope. See here: jsbin.com/IWOKUGi/7/edit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.