3
<input type='text' ng-model='foo' my-dir='customFunction' />
{{foo}}


.directive('myDir',function(){
     scope:{ customFunc : "&myDir"},
 });

Now the scope will be overridden with myDir and foo won't be updated on the screen. But still each control that has my-dir attribute should have customFunction in an isolated scope.

Is it possible?

Alex Osborn
  • 9,831
  • 3
  • 33
  • 44
iLemming
  • 34,477
  • 60
  • 195
  • 309
  • What exactly are you trying to accomplish? Are you trying to attach a directive to an input field and you want the directive to be able to call a method on the parent scope? If so, you don't need an isolate scope -- isolate scopes [have issues with ng-model](http://stackoverflow.com/questions/11896732/ngmodel-and-component-with-isolated-scope). – Mark Rajcok Apr 15 '13 at 21:15
  • I'm trying to have a directive restricted to attribute that could call an arbitrary function set in that attribute – iLemming Apr 15 '13 at 21:18
  • Depending on where the directive will be used will determine how you write it. If the directive will not be used with other directives, you can use an isolate scope. If it will be used with other directives (like ng-repeat, ng-model, and others) you may need to create a directive that either does not create a new scope, or creates a child scope (not an isolate scope). For the non-isolate cases, you can pass the name of the function via the attribute value, then inside your link function, call it using [$eval](http://docs.angularjs.org/api/ng.$rootScope.Scope#$eval): `scope.$eval(attrs.myDir)` – Mark Rajcok Apr 15 '13 at 21:26
  • how would I create a child scope? – iLemming Apr 15 '13 at 21:31
  • In your directive, `scope: true` -- this creates a new child scope that prototypically inherits from the parent scope. The default (`scope: false`) creates no new scope -- the directive uses the same scope as the element it is used on. – Mark Rajcok Apr 15 '13 at 21:34

1 Answers1

3

As mentioned in the comments above, one directive probably won't work everywhere. If the directive will be used with other directives like ng-model, ng-repeat, etc., an isolate scope probably won't work. Here's an example of a directive that uses $eval, and does not create a new scope:

<div ng-controller="MyCtrl">
  <input type='text' ng-model='foo' my-dir='customFunction'>
  <br>foo={{foo}}
</div>


app.directive('myDir', function() {
    return {
        link: function(scope, element, attrs) {
            scope.$eval(attrs.myDir);
        },
    }
});


function MyCtrl($scope) {
    $scope.customFunction = alert('hi');
    $scope.foo = '22';
}

Fiddle

See also When writing a directive in AngularJS, how do I decide if I need no new scope, a new child scope, or a new isolated scope?

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492