zoukankan      html  css  js  c++  java
  • AngularJS自定义Directive不一定返回对象

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

    angular.module('modulename')
        .directive('myDirective', function(){
            return {
                restrict: 'EA', //E表示element, A表示attribute,C表示class,M表示commnent,即注释
                scope:{
                    title: '@' //@读属性值,=双向绑定,&用户函数
                }
                template: '<div>{{myVal}}</div>',
                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>

  • 相关阅读:
    源码阅读-logback的StaticLoggerBinder如何提供ILoggerFactory的实现类
    源码阅读-logback解析之对接日志门面slf4j
    不可变对象 -final-unmodifiableX
    安全发布对象
    线程安全性-原子性-可见性-有序性
    并发相关基础知识
    并发与高并发介绍
    Spring源码解析-ioc容器的设计
    微服务架构概述
    获取当前时间到毫秒
  • 原文地址:https://www.cnblogs.com/darrenji/p/5084105.html
Copyright © 2011-2022 走看看