欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

angular中transclude和scope之间的关系

程序员文章站 2022-05-29 21:36:42
...
直接上代码

app.controller('MainCtrl', function($scope) {
  $scope.person = {
    name: 'John Doe',
    profession: 'Fake name'
  };

  $scope.header = 'Person';
});

app.directive('person', function() {
  return {
    restrict: 'EA',
    scope: {
      header: '='
    },
    transclude:true,
    template: '<div ng-transclude></div>',
    link: function(scope, element, attrs) {
      scope.person = {
        name: 'Directive Joe',
        profession: 'Scope guy'
      };

      scope.header = 'Directive\'s header';
    }
  };
});


<body ng-controller="MainCtrl">
  <person header="header">
    <h2>{{header}}</h2>
    <p>Hello, I am {{person.name}} and,</p>
    <p>I am a {{person.profession}}</p>
  </person>
</body>

以上代码会变成
<body ng-controller="MainCtrl" class="ng-scope">
  <person header="header" class="ng-isolate-scope"><div ng-transclude="">
    <h2 class="ng-scope ng-binding">Directive's header</h2>
    <p class="ng-scope ng-binding">Hello, I am John Doe and,</p>
    <p class="ng-scope ng-binding">I am a Fake name</p>
  </div></person>
</body>

即原有的属性不会被替换,而原来没有的属性,则会使用新的

如果想通过指令来控制接受父级的scope值还是子集的scope值,可以通过如下代码区分
app.directive('person', function() {
  return {
    restrict: 'EA',
    scope: {
      header: '='
    },
    transclude:true,
    link: function(scope, element, attrs, ctrl, transclude) {
      scope.person = {
        name: 'Directive Joe',
        profession: 'Scope guy'
      };

      scope.header = 'Directive\'s header';
      transclude(scope.$parent, function(clone, scope) {
        element.append(clone);
      });
    }
  };
});


app.directive('person', function() {
  return {
    restrict: 'EA',
    scope: {
      header: '='
    },
    transclude:true,
    link: function(scope, element, attrs, ctrl, transclude) {
      scope.person = {
        name: 'Directive Joe',
        profession: 'Scope guy'
      };

      scope.header = 'Directive\'s header';
      transclude(scope, function(clone, scope) {
        element.append(clone);
      });
    }
  };
});

以上两组代码中,transclude传递的参数中,第一个参数分别传递的为scope.$parent和scope

参考自
http://angular-tips.com/blog/2014/03/transclusion-and-scopes/