博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AngularJS自定义Directive不一定返回对象
阅读量:4482 次
发布时间:2019-06-08

本文共 1529 字,大约阅读时间需要 5 分钟。

 

AngularJS中,当需要自定义Directive时,通常返回一个对象,就像如下的写法:

 

angular.module('modulename')    .directive('myDirective', function(){        return {            restrict: 'EA', //E表示element, A表示attribute,C表示class,M表示commnent,即注释            scope:{                title: '@' //@读属性值,=双向绑定,&用户函数            }            template: '
{
{myVal}}
', templateUrl: 'app/sample.html', controller: 'myController', link:function($scope, element, attrs){}//DOM操作 }; })

 

也可以直接返回函数。实际上返回的是link对应的函数。

 

var app=angular.module('superhero',[]);app.directive("enter", function(){   return function(scope, element){       element.bind("mouseenter", function(){           console.log('I am inside of you');       })   }});app.directive("leave", function(){    return function(scope, element){        element.bind("mouseleave", function(){            console.log('i am leaving on a jet plane');        })    }})

 

以上,实际上return没有返回对象,而是返回了一个函数。

在页面中按如下调用:
<div enter leave>I am content</div>

 

另外,link函数还有一个attrs形参用来描述所有的属性,通过"attrs.属性名"来获取属性值。

 

app.directive("enter", function(){   return function(scope, element, attrs){       element.bind("mouseenter", function(){           element.addClass(attrs.enter);       })   }});app.directive("leave", function(){    return function(scope, element,attrs){        element.bind("mouseleave", function(){            element.removeClass(attrs.enter);        })    }})

 

在页面中按如下调用:

<div enter="panel" leave>I am content</div>

转载于:https://www.cnblogs.com/darrenji/p/5084105.html

你可能感兴趣的文章
IntelliJ IDEA2018.1、2017.3激活
查看>>
Orchard后台控制面板的介绍
查看>>
大二下第一周----开学测试
查看>>
javaweb-servlet生成简单的验证码
查看>>
apache+php+mysql环境搭建时,phpinfo里面没有mysql解决办法
查看>>
2018.10.2浪在ACM 集训队第三次测试赛
查看>>
sun.misc.Unsafe 详解
查看>>
食堂排队问题的一个实现
查看>>
Git 回滚代码的正确姿势
查看>>
构造函数、析构函数、虚析构函数、纯虚析构函数要点
查看>>
Python批量获取京东商品列表信息
查看>>
2017.7.10 C组总结
查看>>
SourceTree下载 及使用
查看>>
MyEclipse下安装FatJar打包工具
查看>>
什么是域名-视频讲解?
查看>>
大道至简第六章-从编程到工程
查看>>
单元测试——隔离神器:mockito
查看>>
[Web Tools] 实用的Web开发工具
查看>>
ContentProvider
查看>>
欢迎来到Attention的博客
查看>>