一般来讲 directive名字遵循一下规则:
1.忽略以x-和data-为元素/属性的前缀
2.转化“:”,“-”,“_”命名为驼峰命名
如下所示
<div ng-controller="Controller"> Hello <input ng-model='name'> <hr/> <span ng-bind="name"></span> <br/> <span ng:bind="name"></span> <br/> <span ng_bind="name"></span> <br/> <span data-ng-bind="name"></span> <br/> <span x-ng-bind="name"></span> <br/> </div>
angular.module('docsBindExample', [])
.controller('Controller', ['$scope', function($scope) {
$scope.name = 'Max Karl Ernst Ludwig Planck (April 23, 1858 – October 4, 1947)';
}]);
transclude
makes the contents of a directive with this option have access to the scope outside of the directive rather than inside.
(ng-transclude="true" 是当前directive模板内容访问的是外部scope而不是内部scope)
示例:
script.js angular.module('docsTransclusionExample', []) .controller('Controller', ['$scope', function($scope) { $scope.name = 'Tobias'; }]) .directive('myDialog', function() { return { restrict: 'E', transclude: true, scope: {}, templateUrl: 'my-dialog.html', link: function (scope) { scope.name = 'Jeff'; } }; });
index.html
<div ng-controller="Controller">
<my-dialog>Check out the contents, {{name}}!</my-dialog>
</div>
my-dialog.html
<div class="alert" ng-transclude></div>
运行结果:Check out the contents, Tobias!
The transclude
option changes the way scopes are nested. It makes it so that the contents of a transcluded directive have whatever scope is outside the directive, rather than whatever scope is on the inside. In doing so, it gives the contents access to the outside scope.
如果想以上代码运行结果为:Check out the contents, Jeff!
则directive不能建立自己独立scope:
script.js angular.module('docsTransclusionExample', []) .controller('Controller', ['$scope', function($scope) { $scope.name = 'Tobias'; }]) .directive('myDialog', function() { return { restrict: 'E', transclude: true, //scope: {}, templateUrl: 'my-dialog.html', link: function (scope) { scope.name = 'Jeff';//scope继承父scope } }; });
directive中require选项,比如require:"^^myTabs",“^^”前缀意味着myTabs会在父元素中的controller查找,单个“^”意味着在自身或者父元素中查找,没有前缀则只在自身中查找,以上如果没有查找到就会抛错。
如果directive中需要包含多个controller,则link function第四个参数为一个数组类型
angular.module('docsTabsExample', []) .directive('myPane', function() { return { require: ['^^myTabs', 'ngModel'], restrict: 'E', transclude: true, scope: { title: '@' }, link: function(scope, element, attrs, controllers) { var tabsCtrl = controllers[0], modelCtrl = controllers[1]; tabsCtrl.addPane(scope); }, templateUrl: 'my-pane.html' }; });
controller和link的不同之处在于:controller向外暴露API,link函数通过require选项与controller交互