在 Angular 1.6.x components 中仅使用隔离范围:
组件只控制自己的视图和数据:组件应该
永远不要修改任何超出其自身范围的数据或 DOM。一般,
在 AngularJS 中,可以在应用程序的任何地方修改数据
通过范围继承和监视。这个很实用,但也可以
当不清楚应用程序的哪个部分是时会导致问题
负责修改数据。这就是为什么组件指令
使用隔离范围,所以整个范围的操作不是
可能。
因此,要完成这项工作,您需要使用指令而不是组件。您要包含的 div 本身需要是一个指令,才能更改工具栏指令的父范围。您要做的是将一个指令嵌入到另一个指令中,并使用共享作用域来更改父作用域。
这篇文章对于您要完成的工作来说是一个非常好的资源。我将从这里开始:https://www.airpair.com/angularjs/posts/transclusion-template-scope-in-angular-directives
我已经更改了该文章中的示例 Codepen,以向您展示它的工作原理:http://codepen.io/jdoyle/pen/aJQpYo
如果您选择列表中的项目,您可以看到标题名称更改为所选内容。
angular.module("ot-components", [])
.controller("AppController",($scope)=> {
//Normally, this data would be wrapped in a service. For example only.
$scope.header = "Marketing";
$scope.areas = {
list: [
"Floorplan",
"Combinations",
"Schedule",
"Publish"
],
current: "Floorplan"
};
})
.directive("otList", ()=> {
return {
scope: false, // this is one of the major changes
template:
`<ul class="ot-list">
<li class="ot-list--item"
ng-repeat="item in items"
ng-bind="item"
ng-class="{'ot-selected': item === selected}"
ng-click="selectItem(item)">
</li>
</ul>`,
link: (scope, elem, attrs) => {
scope.items = JSON.parse(attrs.items);
scope.selected = attrs.selected;
scope.selectItem = (item) => {
scope.selected = item;
scope.$parent.header = item; // this is the other major change
};
}
};
})
.directive("otSite", ()=> {
return {
scope: true, // another major change
transclude: true,
template:
`<div class="ot-site">
<div class="ot-site--head">
<img class="ot-site--logo" src="//guestcenter.opentable.com/Content/img/icons/icon/2x/ot-logo-2x.png">
<h1>{{header}}</h1>
</div>
<div class="ot-site--menu">
</div>
<div class="ot-site--body" ng-transclude>
</div>
<div class="ot-site--foot">
© 2015 OpenTable, Inc.
</div>
</div>`
};
});