`
LiYunpeng
  • 浏览: 938611 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

angular中transclude和scope之间的关系

阅读更多
直接上代码

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/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics