我可以使指令的嵌入范围与父母相同吗? [英] Can I make the transcluded scope of a directive be the same as the parents?

查看:22
本文介绍了我可以使指令的嵌入范围与父母相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些 html 角度:

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.

一切正常.

但现在我想创建一个将元素包装在 div 中的指令(因此它显示在深灰色背景中).

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

我创建了一个指令,将嵌入元素并用 div 包裹它们:

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>'
    };
});

当然,这个指令将为嵌入的元素创建一个新的范围.input 元素不再指点击按钮时将获得输出的内容属性.

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.

我可以通过将 $parent 引用为:

I can make it work by referencing $parent as :

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

但是,我不想这样做.我想在用我的新指令包装时尽可能保持 html 不变.

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?

这是一个 jsFiddle 的问题.

推荐答案

与其试图让被嵌入的元素引用父作用域,不如使用对象属性:

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.)

这篇关于我可以使指令的嵌入范围与父母相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆