Can I make the transcluded scope of a directive be the same as the parents?

元气小坏坏 提交于 2019-12-11 12:40:50

问题


Say I have some html in angular :

 <input type='text' ng-model='stuff' /> {{stuff}}
 <button class="primary" ng-click='dothestuff()'>Do the stuff</button>

With the following in the controller :

$scope.stuff = 'arf';
$scope.dothestuff = function () {
    $window.alert($scope.stuff);    
};

This code will take I enter in the input and output it when I hit the button.

All works well.


But now I want to create a directive that wraps the elements in a div (so it shows in a dark grey background).

I create a directive that will transclude the elements and wrap them with the div:

testapp.directive('wrapper', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: false,
        transclude: true,
        template: '<div style="background:#666"><div ng-transclude></div></div>'
    };
});

But of course, this directive will then create a new scope for the transcluded elements. The input element no longer refers to the stuff property that will get output when hitting the button.

I can make it work by referencing $parent as :

 <input type='text' ng-model='$parent.stuff' /> {{stuff}}

However, I would prefer not to. I want to leave the html as untouched as possible when wrapping with my new directive.

How can I make the transcluded elements refer directly to the parent scope?

Here is a jsFiddle with the problem.


回答1:


Instead of trying to make the transcluded elements refer to the parent scope, it is better to use object properties:

$scope.obj = {stuff: 'arf'};

fiddle

Since the transcluded scope prototypically inherits from the parent scope, the transcluded scope has access to all of the parent scope properties. By using object properties, "writes" go to the parent scope properties. (When using primitives, "writes" create new properties on the child transcluded scope, which hide/shadow the parent scope properties of the same name.)



来源:https://stackoverflow.com/questions/17927476/can-i-make-the-transcluded-scope-of-a-directive-be-the-same-as-the-parents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!