Angular Isolate Scope for nested directives

2019-09-18 19:49发布

I'm attempting to set up an angular app with three directives - container, getter and setter. I've put it up at http://plnkr.co/edit/CoYLuVbiZTFWvNsN5r5L?p=preview

<container>
    <getter name="first"></getter>
    <getter name="second"></getter>
    <setter name="setter"></setter>
</container>

Container has a scope with the variable value which can be read by getter and setter. getter displays the value whilst setter both displays and changes the value.

    angular.module("app").directive('container', function() {
      return {
        scope: {},
        template: '<h1>Container <input ng-model="value"/></h1><div ng-transclude>SCOPED1</div>',
        transclude: true,
        controller: ["$scope", "$window", function($scope, $window){
            $scope.value = "Hello"
        }]
      };
    });

Both getter and setter have their own isolate scope but also have a two-way binding to the container scope to get and set value.

    angular.module("app").directive('getter', function() {
      return {
        require: '^container',
        scope: {
            name: '@',
            value:'='
          },
        template: '<p>I am getter {{name}}, I got {{value}}</p>'
      };
    });

At the moment, getter and setter can access the container scope using $scope.$parent.$parent.value but that seems way too clunky. I thought using scope:{value:'='} would set up two way bindings but apparently not.

What am I doing wrong?

http://plnkr.co/edit/CoYLuVbiZTFWvNsN5r5L?p=preview

1条回答
祖国的老花朵
2楼-- · 2019-09-18 20:19

The directive isolate scope is not automatically linked to variables in the parent scope. You must tell the directive that value is supposed to be value in the parent scope, the same way you supply the directive name.

<container value="value">
    <getter name="first" value="value"></getter>
    <getter name="second" value="value"></getter>
    <setter name="setter" value="value"></setter>
</container>
查看更多
登录 后发表回答