[Angularjs]自定义指令

写在前面

指令的作用可以简单的描述为实现语义化的标签,比如你在移动端h5应用中,有个经常用的功能,比如通讯录的功能,不同的页面都要用到,这时你可以将其封装为指令,在使用的时候可以通过这样<friends></friends>的语义化的标签直接在页面中使用即可。

例子

首先实现一个Helloworld的例子,让我们先上手自定义指令,先体会下指令的妙处。

定义指令helloword

var app = angular.module('app_store', ['ngRoute', 'StoreService', ]);
//自定义指令
app.directive('helloworld', function () {
    return {
        restrict: 'E',
        template: '<h1>Hello world</h1>',
        replace: true
    };
});

使用指令

<helloworld></helloworld>

效果

生成的html

<div ng-view="" class="ng-scope">
    <h1 class="ng-scope">Hello world</h1>
</div>

看到生成的标签,你大概已经猜出template的作用了。

restrict: 说明指令在HTML中的渲染形式,选项有"A"、"E" 和 "C", "M" ,分别代表 attribute、element、class和comment(默认值为"A"),对应首字母记起来也很容易。

示例

A:<div helloworld></div>

C:<div class="helloworld"></div>

M:<!-- helloworld -->

transclude

指令的作用是把自定义的指令发标签替换成浏览器能够认识的标签,如果自定义的标签内部出现了子标签,那么transclude就可以帮我进行处理了。

//自定义指令
app.directive('helloworld', function () {
    return {
        restrict: 'E',
        template: '<div> Hello world<span ng-transclude></span></div>',
        transclude: true
    };
});

在html上使用

<helloworld>
    <br />
    <span>子标签1</span><br />
    <span>子标签2</span><br />
</helloworld>
<helloworld>
</helloworld>

生成的html

link

在指令中负责执行dom操作和注册事件监听器。

参数

scope:指令的scope的引用。scope变量在初始化时是不被定义的,link方法会注册监视器监视值变化事件。

element:包含指令的dom元素的引用,link方法一般通过jquery操作实例。

controller:在有嵌套指令的情况下使用。这个参数作用在把子指令的引用提供给父指令,允许指令之间进行交互。

scope

创建指令的作用范围,scope在指令中作为属性标签传递。scope是创建可以复用指令的必备条件,每个指令(不论是处于嵌套指令的哪一级)都有其唯一的作用域,它不依赖于父scope。scope对象定义names和types变量。

“@”:(值传递,单向绑定),指令会检索从父级scope中传递而来字符串中的值。指令可以使用该值但无法修改,是常用的变量。

“=”:(引用,双向绑定),指令检索scope中的引用取值。值可以是任意类型的,包括符合对象和数组。指令可以更改父级scope中的值,所以当指令需要修改父级scope中的值时我们就需要这种类型。

“&”:(表达式)在父级scope中起作用的表达式,它允许指令实现比修改值更高级的操作。

实现friends自定义指令

var app = angular.module('app_store', ['ngRoute', 'StoreService', ]);

//自定义指令
app.directive('friends', function () {
    return {
        restrict: 'E',
        controller:'FriendsController',
        templateUrl: '../Scripts/Views/friends.html',
        transclude: true,
        scope: {
            type:"&"
        }
    };
});

friends模板

<div class="address_serace">
    <input class="form-control" ng-change="" ng-model="friendKey" placeholder="Search">
</div>
<div class="address_div">
    <dl class="address_dl" ng-repeat="item in orders">
        <dt class="address_checkbox">
            <img class="address_check" src="../Images/icon-xx01@2x.png" />
        </dt>
        <dt class="address_user"><img class="address_user" src="../Images/dingy.png" /></dt>
        <dd class="address_font">
            <p class="address_font_t">{{item.Name}}</p>
            <p>From:{{item.Price}}</p>
        </dd>
    </dl>

</div>

在路由#/home下使用指令friends

<friends></friends>

浏览页面

这里为了方便直接将模板存在一个html页面里面了,你也可以通过拼接字符串的形式将标签写在自定义指令里面。

总结

今天抽空将指令这块补一下。

参考

http://www.cnblogs.com/powertoolsteam/p/angularjs-custom-directive.html

原文地址:https://www.cnblogs.com/wolf-sun/p/5373762.html