A
A
Alexey Berdnikov2017-05-31 15:25:58
Angular
Alexey Berdnikov, 2017-05-31 15:25:58

How can you find out in the component template whether something was passed through transclude to hide or display some elements?

Angular 1.*
For example, in a block box if content is passed, so that a button appears in the header to collapse / expand content
In the component template:

<div>
    <div class="header">
    <div ng-if="{{%ctrl.isTransclude}}"><i class="fa fa-arrow-plus"></i></div>
        {{$ctrl.model.header}}
    </div>
    <div class="body" ng-transclude></div>
</div>

1) If in the page template (with content):
<block model="model">
    content
</block>

then as a result we get
<div>
    <div class="header">
        <div><i class="fa fa-arrow-plus"></i></div>
        {{$ctrl.model.header}}
    </div>
    <div class="body">
        content
    </div>
</div>

2) If in the page template (no content):
<block model="model">
</block>

then as a result we get
<div>
    <div class="header">
        {{$ctrl.model.header}}
    </div>
</div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Grebenshchikov, 2017-05-31
@Groove

You can try to do it through slots:

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
  <meta charset="UTF-8">
  <title>Angular Test</title>
</head>
<body ng-controller="BodyCtrl as vm">
<div test-widget>
  <test-widget-title>Hello!</test-widget-title>
  <test-widget-body>Widget 1</test-widget-body>
</div>
<div test-widget>
  <test-widget-body>Widget 2</test-widget-body>
</div>
<script src="https://unpkg.com/[email protected]/angular.js"></script>
<script type="text/javascript">
angular
  .module('app', [])
  .controller('BodyCtrl', function() {})
  .directive('testWidget', function() {
    return {
      restrict: 'A',
      scope: {},
      transclude: {
        'title': '?testWidgetTitle',
        'body': 'testWidgetBody'
      },
      template: '' +
        '<div>BEGIN</div>' +
        '<div ng-if="vm.hasTitle">' +
        '  TITLE: <b ng-transclude="title"></b>' +
        '</div>' +
        '<div ng-transclude="body"></div>' +
        '<div>END</div>' +
        '<p></p>',
      controllerAs: 'vm',
      controller: function($transclude) {
        var vm = this;
        vm.hasTitle = $transclude.isSlotFilled('title');
      },
      link: function(scope, elem, attrs, ctrl, $transclude) {
        //var vm = scope.vm = {};
        //vm.hasTitle = $transclude.isSlotFilled('title');
      }
    };
  });
</script>
</body>
</html>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question