我可以做一个指令的transcluded范围是一样的父母? [英] Can I make the transcluded scope of a directive be the same as the parents?

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

问题描述

说我有角一些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);    
};

这code将我在输入输入和输出,当我按下按钮。

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

我创建了一个指令,将transclude的元素,并与他们包裹在 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>'
    };
});

不过,当然,这个指令将然后创建为transcluded元素的新范围。在输入元素不再是指物业的东西击中按钮时,将获得的输出。

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

不过,我想preFER都不到。我要离开的HTML作为原封不动地与我的新指令时包装

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

我怎样才能让transcluded元素直接引用父作用域?

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

下面是一个的jsfiddle 的问题。

推荐答案

而不是试图让transcluded元素指父范围,最好是使用对象属性:

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

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

<大骨节病> 小提琴

由于transcluded范围<一个href=\"http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs\">prototypically继承父的范围内,该范围transcluded访问所有父作用域属性。通过使用对象属性,写转到父作用域属性。 (当使用原语,写道:创建子transcluded范围,其中隐藏/阴影的同名父作用域属性新的属性。)

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

这篇关于我可以做一个指令的transcluded范围是一样的父母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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