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: '', link: function(scope, element, attrs) { scope.person = { name: 'Directive Joe', profession: 'Scope guy' }; scope.header = 'Directive\'s header'; } }; });
{{header}}
Hello, I am {{person.name}} and,
I am a {{person.profession}}
以上代码会变成
Directive's header
Hello, I am John Doe and,
I am a Fake name
即原有的属性不会被替换,而原来没有的属性,则会使用新的
如果想通过指令来控制接受父级的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/