Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding directive scope makes the rest non-updateable

There's a directive called foo which is defined like this:

<div ng-app="app" ng-controller="mainController">
   {{ name }}

   <foo param="123"></foo>
</div>

And here's the relevant initialization fragment:

var app = angular.module('app', []);
app.controller('mainController', function($scope){
    $scope.name = 'Initial name';
});

app.directive('foo', function(){
    return {
        restrict : 'E',
        controller : function($scope){
            $scope.name = 'Name defined in directive';
            console.log($scope.param); // undefined
        }
    };
});

That works as expected and overrides Initial name with Name defined in directive.

However, since there's param attribute I wanted to access its value. So I did one way binding like this:

    return {
        restrict : 'E',
        controller : function($scope){
            $scope.name = 'Name defined in directive';
            console.log($scope.param); // 123 as expected
        },
        scope : {
          param : "@"
        }
    }

And that broke the updating of the parent scope. Now when running this, it renders Initial name instead of expected Name defined in directive. So what's the problem here?

like image 242
Yang Avatar asked Mar 27 '26 12:03

Yang


1 Answers

When you use the scope option, you create an isolate scope which is by definition, separate from the parent scope.

You will either need to add name to your isolate scope and pass it in just like param OR you will need to remove the scope and define param on the parent scope.

Here's what the Angular docs have to say about isolate scopes:

As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in.

Note: Normally, a scope prototypically inherits from its parent. An isolated scope does not. See the "Directive Definition Object - scope" section for more information about isolate scopes.

like image 186
Anid Monsur Avatar answered Mar 29 '26 11:03

Anid Monsur



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!