angular1.x的directive

转载于: 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(连接)了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值