我是伊只雄熊

导航

AngularJS transclude 理解及例子

一、概念理解 

  transclude可以在指令中让使用者自定义模板,也就是说,指令中模板的一部分,让指令的使用者动态指定;与指定中的Scope属性值为{}时候的作用类似,scope属性让指令使用者动态制定属性数据和事件,但是这里是模板,使用scope属性不合适。

  也就是说,如果你在定义指令的时候,想要它在具体使用时中间加一些内容,那么你就要用transclusion。

  使用时需要通过以下两点:

  1、在指令的template中通过属性或者元素的方式标记放置动态内容的位置,比如<ng-transclude></ng-transclude>;ng-tranclude决定了在什么地方放置嵌入部分。

  2、在指令的返回对象中增加transclude: true

  也就是说,取出自定义指令中的内容(就是写在指令里面的子元素),以正确的作用域解析它,然后再放回指令模板中标记的位置(通常是ng-transclude标记的地方)。

二、transclude与作用域

   在定义一个指令时,如果不显式声明scope,那么指令的作用域就是父作用域。如果声明scope:true或者scope:{},那么指令会生成一个自己的作用域,前者是原型继承,后者是独立作用域。使用transclusion,会生成一个新的作用域,直接原型继承于父作用域。

三、例子

1、入门例子

<body ng-app="myApp">
  <div class="a">
   <my-transclusion name="huyx">嵌入的内容</my-transclusion>
</div>
</body>
angular.module('myApp', []).directive('myTransclusion', function () {
    return {
      restrict: 'E',
      transclude: true,
      scope: { name:'@' },
      template: '<div>' +
                  '<div>{{name}}</div><br>' +
                  '<div ng-transclude></div>' +
                '</div>'
    };
  });

  运行结果:

     

  即,把使用指令的地方的内容,这里是“”嵌入的内容“,放到了指令模板中ng-transclude位置。

    生成页面源码:

 2、复杂点例子

  button-bar指令使用的地方的内容(即下边的两个button),替换到指令模板ng-transclusion的地方。而且,在项目不同的地方多出使用该指令,根据需要可以指定不同的动态内容,插入指定的模板指定位置,而指定的其他部分可以共用。

<div ng-controller="parentController">
  <button-bar>
    <button class="primary" ng-click="onPrimary1Click()">{{primary1Label}}</button>
    <button class="primary">Primary2</button>
  </button-bar>
</div>
var testapp = angular.module('testapp', []);
testapp.controller('parentController', ['$scope', '$window', function($scope, $window) {
  console.log('parentController scope id = ', $scope.$id);
  $scope.primary1Label = 'Prime1';
  $scope.onPrimary1Click = function() {
    $window.alert('Primary1 clicked');
  };
}]);
testapp.directive('primary', function() {
  return {
    restrict: 'C',
    link: function(scope, element, attrs) {
      element.addClass('btn btn-primary');
    }
  }
});
testapp.directive('buttonBar', function() {
  return {
    restrict: 'EA',
    template: '<div class="span4 well clearfix"><div class="pull-right" ng-transclude></div></div>',
    replace: true,
    transclude: true
  };
});

 

posted on 2018-03-03 23:19  我是伊只雄熊  阅读(291)  评论(0编辑  收藏  举报