angularJS directive自定义标签和属性

来源:互联网 发布:今日头条 算法工程师 编辑:程序博客网 时间:2024/04/29 13:52

directive可以自定义标签和属性,首先看一个例子:

<html ng-app="testModule"><head>    <meta charset="utf-8">    <title>My HTML File</title>    <link rel="stylesheet" href="css/app.css">    <link rel="stylesheet" href="css/bootstrap.css">    <script src="lib/angular/angular.js"></script></head><body ng-controller="testController">    <input type="text" ng-model="person">    <hello person="person"><div>    {{person}}</div>    </hello><p>{{a}}</p><script>    var testModule=angular.module('testModule',[]);    testModule.controller('testController',function($scope){    $scope.person="Tony";    });    testModule.directive('hello',function(){return{            restrict: 'E',            transclude: true,            scope: {               'personName': '=person'            },            template:'<div ng-transclude></div><input type="button" value="click" ng-click="toggle()"><div ng-show="isShow">{{personName}} say hello to us</div>',            link:function(scope,element,attrs){                scope.toggle=function toggle(){                    scope.isShow=!scope.isShow;        }    }};    });</script></body></html>
1、restrict

'E': 表示元素,例如<hello></hello>

'A':表示属性,例如<div hello=""></div>

'C'表示样式,例如<div class=hello:""></div>

'M'表示注释,

2、template

template中放置新的html文本,也可以为文件路径

3、transclude

transclude为true时,和ng-transclude一起使用,template中标记ng-transclude的地方用放置hello标签中原来的内容

4、scope

scope:{

    name1:'=name1',

    name2:'@name2',

    name3:'&name3'

}

'=name1':,name1为取标签中的属性名为name1的值对于$scope;若name1为空,即‘=’,则取同名属性的值的$scope,且实现了双向绑定。

'@name2':取标签中name2属性值,若<hello name2="nname22"></hello>,则取的值为nname22。

'&name3':name3为controller中的$scope同名方法。

5、link

若需要执行函数,则在link中定义

函数中的参数scope即上面定义的scope,element即执行directive的元素,attrs为元素属性

0 0