Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the scope of my element from an attribute directive?

<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?

like image 993
iLemming Avatar asked Dec 07 '25 00:12

iLemming


1 Answers

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?

like image 152
Mark Rajcok Avatar answered Dec 08 '25 15:12

Mark Rajcok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!