[英]Angular 1.5 Component template with slot for child-dom
我正在嘗試制作一個可重用的自包含 angular 1.5 組件,作為其他頁面內容的包裝器。 當一個值改變時,它會切換子內容。 隱藏和顯示內容的解決方案不是問題,而是如何制作一個可重用的組件,可以處理將子項注入組件模板而不是覆蓋模板。
頁面.html
<div class="some page">
<my-cmp value="false">
<p>this static content is toggled by my-cmp</p>
<div>more stuff</div>
<ul>
<li>no limits</li>
</ul>
</my-cmp>
</div>
當值改變時,組件應該改變頁面上的內容。
<div class="some page">
<my-cmp value="true">
<div>
<h1>Content is hidden</h1>
<button>Show content</button>
</div>
</my-cmp>
</div>
我一直在閱讀 angular 1.5 文檔,但沒有找到任何這樣做的例子。 我遇到的問題是子內容在我的組件模板中覆蓋了內容,我無法告訴組件放置子內容的確切位置。 組件應該能夠在兩種狀態之間自由切換。
我的-cmp.html
<div class="my-cmp">
<div ng-if="showContent">
<!--child content should be inserted here by the component -->
<!-- how do i tell the my-cmp template i want child elements injected here? -->
<!-- this is the only part i'm missing -->
</div>
<div ng-if="!showContent">
<h1>Content is hidden</h1>
<button>Show content</button>
</div>
</div>
我設法找到了一些顯示如何執行此操作的舊文檔。 transclude: true,
在組件中是需要的。
我的 cmp.js
(function() {
angular.module("app").component("my-cmp", {
templateUrl: "views/tmpl/components/my-cmp.html",
controller: [myCmp],
restrict: 'E',
transclude: true,
binding: {
show: '<',
}
});
function myCmp() {...}
})();
我的-cmp.html
<div class="my-cmp">
<div class="content" ng-if="showContent" ng-transclude>
<!-- content is added by children passed in -->
</div>
<div ng-if="!hideContent">
<h1>Content is hidden</h1>
<button>Show content</button>
</div>
</div>
將ng-transclude
作為屬性添加到作為目標的元素,將告訴 angular 在此位置注入子 DOM 元素,而不是覆蓋您的模板。
(function() {
angular
.module('app.my-component')
.component('myCmp', {
transclude: true,
bindings: {
showContent: '='
},
templateUrl: 'my-cmp.html',
controller: 'MyCmpController'
});
})();
(function() {
angular
.module('app.my-component')
.controller('MyCmpController', MyCmpController);
/*@ngInject*/
function MyCmpController($scope) {
$scope.showHiddenContent = showHiddenContent;
function showHiddenContent() {
$scope.showContent = !$scope.showContent;
}
}
})();
在 HTML 中:
<div class="some-page">
<my-cmp show-content="isHidden">
<p>this static content is toggled by my-cmp</p>
<div>more stuff</div>
<ul>
<li>no limits</li>
</ul>
</my-cmp>
</div>
我的-cmp.html
<div class="my-cmp">
<div class="content" ng-if="showContent" ng-transclude> <!-- ng-show="showContent" -->
<!-- content is added by children passed in -->
</div>
<div ng-if="!showContent"> <!-- ng-hide="!showContent" -->
<h1>Content is hidden</h1>
<button type="button" ng-click="showHiddenContent()">Show content</button>
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.