[英]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永远不会更新。
谢谢!
我在这里阅读了关于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:有很多链接。
仅提及两个:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.