angularjs directive

关键词:

 restrict   :"A" 默认后面加"E",代表element,自己定义的directive名字为标签名  A属性(attribute) C(class)
 replace    :bool  默认为false,当为true时,标签名不是自己定义的名字,为template的内容
 template   :"<div></div>" 将自己定义的标签名转化为html元素
priority :int 指示执行指令的优先级,数字越大优先级越高
terminal :bool 是否运行比自己优先级低的
transclude :bool 嵌入,为true时,允许把html指令中的dom运用到该指令的template中:"<div>11111<div ng-transclude></div></div>"
templateUrl:string,模版链接
require :"directivename" 访问指定指令,会传给link函数的第四个参数
controller :string or function(){}
指令内部controller,给指令提供public的方法给外部调用

一般用法:

 var aj = angular.module("aj", []);
    aj.directive("enter", function () {
        return function (scope, element, attrs) {
            element.bind("mouseenter", function () {
                element.addClass("cs");
            })
        }
    })
    aj.directive("hello", function () {
        return {
            restrict: 'E', 
            template: "<input ng-model='txt'><div>{{txt}}</div>",
            link: function (scope, element,attrs) {
                scope.$watch("txt", function (val) {     //$watch监听
                    if (val == "err") {
                        element.addClass("cs");
                    }
                })
            }
        }
    })

html中可以这样用:

        <div ng-app="aj">
            <div enter>123</div>
            <hello></hello>
        </div>

directive调用controller中的方法:

HTML:

 <div ng-app="app">
            <div ng-controller="ctrl">
                <div enter="fun2()">im here</div>
            </div>
        </div>

JS:

    app.controller("ctrl", function ($scope) {
        $scope.fun = function () {
            alert(11111);
        }
        $scope.fun2 = function () {
            alert(22222);
        }
    })
    app.directive("enter", function () {
        return function (scope, element,attrs) {
            element.bind("mouseenter", function () {
                //scope.fun();           
                //scope.$apply("fun()");  
                scope.$apply(attrs.enter);
            })
        }
    })

 

posted on 2018-03-16 15:51  段了的弦  阅读(139)  评论(0编辑  收藏  举报