自定义指令directive

时间:2023-03-09 00:21:50
自定义指令directive

1.自定义指令

在angular中,module下面的directive方法用于创建自定义指令,用法:

m1.directive('myTab',function(){

  return {

    restrict : 'AE',

    replace : true,

    templateUrl : '',

};

});

大致用法如上,在directive的第二个参数里面return出一个对象,对象里面有各种属性。

restrict----指定创建的指令是什么类型,A--attr属性指令,E--element标签指令,C---class指令,M---注释指令.常用的就是A和E。

replace---是否用模板来替换元素

templateUrl---指定模板字符串

还有一些:

controller---指令控制器。这里面可以定义一些指定公用的数据和方法。如:

controller : ['$scope',function($scope){
  $scope.name = 'meng';
  $scope.show = function(n){
    alert(n+1);
  }
}],

scope---作用域,共有三个值

默认值false。

表示继承父作用域;

true

表示继承父作用域,并创建自己的作用域(子作用域);

{}

表示创建一个全新的隔离作用域;

隔离作用域中有三种绑定策略--@,=,&

@ --- 使用@(@attr)来进行单向文本(字符串)绑定

= --- 使用=(=attr)进行双向绑定变量

& --- 使用&来调用父作用域中的函数

link:一个函数,用于操作dom,添加事件,指令间相互调用

该函数一共有4个参数,scope,element,attr,reController

scope --- 该指令的作用域

element--- 该指令解析后的顶层元素

attr-- 属性

指令之间交互 通过transclude和require

设置transclude:true之后,就可以通过ng-transclude来嵌套指令

require---字符串代表另一个指令的名字,它将会作为link函数的第四个参数

没有前缀,指令会在自身提供的控制器中进行查找,如果找不到任何控制器,则会抛出一个error

?如果在当前的指令没有找到所需的控制器,则会将null传给link连接函数的第四个参数

^如果在当前的指令没有找到所需的控制器,则会查找父元素的控制器

?^组合

<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://cdn.staticfile.org/angular.js/1.2.10/angular.min.js"></script>
</head>
<body> <outer-directive>
<inner-directive></inner-directive>
<inner-directive2></inner-directive2>
</outer-directive>
<script>
var app = angular.module('myApp', []);
app.directive('outerDirective', function() {
return {
scope: {},
restrict: 'AE',
controller: function($scope) {
this.say = function(someDirective) {
console.log('Got:' + someDirective.message);
};
}
};
});
app.directive('innerDirective', function() {
return {
scope: {},
restrict: 'AE',
require: '^outerDirective',
link: function(scope, elem, attrs, controllerInstance) {
scope.message = "Hi,leifeng";
controllerInstance.say(scope);
}
};
});
app.directive('innerDirective2', function() {
return {
scope: {},
restrict: 'AE',
require: '^outerDirective',
link: function(scope, elem, attrs, controllerInstance) {
scope.message = "Hi,shushu";
controllerInstance.say(scope);
}
};
}); </script> </body>
</html>
m1.directive('myTab',function(){
return {
restrict : 'E',
replace : true,
scope : {
myId : '@',
myData : '='
},
controller : ['$scope',function($scope){
$scope.name = 'meng';
}],
templateUrl : 'temp3.html',
link : function(scope,element,attr){
//console.log(scope.name);
//console.log(element);
//console.log(attr.myId); }
});