繁体   English   中英

Angular指令:隔离范围和跨接是正确的,但指令中的HTML需要继续绑定到父$ scope

[英]Angular Directive: Isolate Scope & Transclude is true, but HTML in the directive needs to continue to bind to parent $scope

首先,我在这里设置一个JSFiddle: http : //jsfiddle.net/qLagkgt5/3/

我希望标题清楚,但基本上,我正在尝试使用指令来帮助可重复的html。 在JSFiddle上的示例中,我使用的是box指令,其中包含space和box-type的选项。

我变成可重复代码的html:

<div class="box">
    <div class="box-inner">
        {{CONTENT GOES HERE}}
    </div>
</div>

带有可选类:

<div class="box spacing-small box-rounded">
    <div class="box-inner">
        {{CONTENT GOES HERE}}
    </div>
</div>

我想做的是:

<box spacing="small" box-type="rounded">
    {{CONTENT GOES HERE}}
</box>

显然,这是一组非常简化的html,不一定需要指令,但这只是说明我所遇到的问题的一个示例。

现在到事物的角度...

这是我的控制器:

app.controller("Ctrl", ["$scope", function($scope) {

    $scope.text = "Starting Text... FOOBAR!";

}]);

这是我的指令:

app.directive("box", function() {
    return {
        restrict: "E",
        transclude: true,
        replace: true,
        scope: {
            spacing: "@",
            boxType: "@"
        },
        template: '<div class="box" ng-class="{\'spacing-{{spacing}}\' : spacing, \'box-{{boxType}}\' : boxType}"> <div class="box-inner" ng-transclude></div></div>'
    }
});

如果我现在使用这样的控制器将指令放在html内:

<div class="wrap" ng-controller="controller">
    {{text}}
    <box spacing="small">
        <input ng-model="text"/>
    </box>
</div>

当我更改框内的输入时, <box>之外的$ scope.text永远不会更新。

  1. 我如何做到这一点,以便在使用此指令时,框中的内容上升到父作用域,而不是孤立的作用域?
  2. 如果我将一个盒子嵌套在另一个盒子中,是否还可以将其移到同一父范围?

谢谢!

我在这里阅读了关于stackoverflow的内容,当我阅读您的帖子时,我的想法立即跳了起来。 上面写着“如果没有点就做错了……”,我会搜索该文章,并在找到它后立即将其发布在这里,但现在我认为我已“修复”了您的代码:

<div ng-app="app" ng-controller="Ctrl">
    <h1><span class="grey">$scope.data.text:</span> {{data.text}}</h1>
    <box spacing="large" box-type="rounded">
        <h2><span class="grey">$scope.text in box directive:</span> {{data.text}}</h2>
        <input ng-model="data.text" />
    </box>
    <box spacing="small" box-type="rounded-shadow">
        <h2><span class="grey">$scope.text in different box directive:</span> {{data.text}}</h2>
        <input ng-model="data.text" />
    </box>
</div>

var app = angular.module("app", []);

app.controller("Ctrl", ["$scope", function($scope) {

    $scope.data = {};
    $scope.data.text = "Starting Text... FOOBAR!";

}]);

app.directive("box", function() {
    return {
        restrict: "E",
        transclude: true,
        replace: true,
        scope: {
            spacing: "@",
            boxType: "@"
        },
        template: '<div class="box" ng-class="{\'spacing-{{spacing}}\' : spacing, \'box-{{boxType}}\' : boxType}"> <div class="box-inner" ng-transclude></div></div>'
    }
});

您必须创建一个对象并将其用于数据绑定。 我现在正在使用“ data.text”并使用此表达式进行绑定。

蒂姆,干杯

PS:有很多链接。

仅提及两个:

AngularJS:如果您的模型中没有使用。(点),那您做错了吗?

AngularJS:ng-model中的点

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM