<div ng-controller="Ctrl">
<my-dir><h3>some existing content</h3></my-dir>
</div>
1. 当scope=true时
angular.module('scopes', [])
.controller('Ctrl', function($scope) {
$scope.title = "hello";
})
.directive('myDir', function() {
return {
restrict: 'E',
replace: true,
template: '<div>{{title}}</div>'
};
});
运行后的DOM为:
2. 当scope=false时
angular.module('scopes', [])
.controller('Ctrl', function($scope) {
$scope.title = "hello";
})
.directive('myDir', function() {
return {
restrict: 'E',
replace: false,
template: '<div>{{title}}</div>'
};
});
运行后的DOM为:
3. 若想保留原有元素的的子元素,需要使用transclude属性
angular.module('scopes', [])
.controller('Ctrl', function($scope) {
$scope.title = "hello";
})
.directive('myDir', function() {
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<div>{{title}}<div ng-transclude></div></div>'
};
});
运行后的DOM为:
指令的子元素<h3>some existing content</h3>被插入指令模板带有ng-transclude标签中。