angular1.x的directive

来源:互联网 发布:python 函数 传入list 编辑:程序博客网 时间:2024/06/04 23:23

转载于: http://damoqiongqiu.iteye.com/blog/1917971

学习directive

<body ng-app="app" ng-controller="MainCtrl">    <my-directive></my-directive></body>

如上图上面自定义标签是无效的。我们要自定义它

指令的作用:实现语义化标签

template && restrict

<script type="text/javascript">    app = angular.module('app', []);    app.controller('MainCtrl', function($scope) {          });    app.directive('myDirective', function() {        return {            restrict: 'ECMA',            template: '<p> this is directive</p>'        }    });</script>

对于以上代码里面的标签,浏览器显然是不认识的,它唯一能做的事情就是无视这个标签。那么,为了让浏览器能够认识这个标签,我们需要使用Angular来定义一个hello指令(本质上说就是自己来把这种玩意儿替换成浏览器能识别的那些标准HTML标签)。

上面的注意点:
restrict: 指令声明方法
这里写图片描述
template: 渲染的元素
如果我们需要替换的HTML标签很长,显然不能用 拼接字符串的方式来写,这时候我们可以用templateUrl来替代template,从而可以把模板写到一个独立的HTML文件中

transclude

<my-directive>        <span>这是原来的文字</span><br/>        <p>这是原来的文字</p><br/>        <div>这是原来的文字</div><br/>    </my-directive> 
<script type="text/javascript">    app = angular.module('app', []);    app.controller('MainCtrl', function($scope) {          });    app.directive('myDirective', function() {        return {            restrict: 'ECMA',            transclude: true,            template: '<p> this is <span ng-transclude></span> directive </p>'        }    });</script>

这里写图片描述

上面的注意点:
要利用这种写法需要设置transclude: true
上面可以看到 <my-directive>还是存在的,如果不想他出现可以加replace:true

scope

当你想要写一个可重复使用的 directive,不能再依赖父 scope,这时候就需要使用隔离 scope 代替。共享 scope 可以直接共享父 scope,而隔离 scope 无法共享父scope

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title></head><body ng-app='app'>    <div ng-controller='myCtrl'>        <my-directive> <span>原来的文字</span></my-directive>    </div></body></html><script type="text/javascript" src="js/angular-1.5.0.min.js"></script><script type="text/javascript">    var app = angular.module('app',[]);    app.controller('myCtrl',['$scope', function($scope){        $scope.name = 'hanker';    }]);    app.directive('myDirective', function(){        return {            restrict: 'ECMA',            template: '<p>xxxxx {{name}} xxxx<span ng-transclude></span>xxxxxxxxx</p>',            transclude: true,            replace: true,            scope: {},        }    });</script>

上面代码显示的是下图 {{name}}就没法编译成hanker
这里写图片描述

compile(编译)和link(连接)

如前所述,指令的本质其实是一个替换过程。好,既然如此,Angular到底是如何进行替换的呢?嗯嗯,这个过程分2个阶段,也就是本节标题所说的compile(编译)和link(连接)了。

原创粉丝点击