zoukankan      html  css  js  c++  java
  • AngularJS中Directive间交互实现合成

    假设需要烹饪一道菜肴,有3种原料,可以同时使用所有的3种原料,可以使用其中2种,也可以使用其中1种。

    如果以Directive的写法,大致是:<bread material1 material2 material3></bread>,或者是<bread material1 material2></bread>...

    由此,我们需要自定义一个名称是bread的directive,以元素的方式呈现;需要自定义名称是material1的direcitve,名称是material2的directive,...

    我们需要在bread这个directive中首先定义好所有的原料即方法,比如有material1, material2, material3,然后在material1这个directive中需要调用bread这个directive中的material1方法。

    这就涉及到了direcitve之间的交互和相互调用了。

    如何交互呢?

    其实,在direcive中为我们提供了一个require字段,此处用来声明需要调用的外部directive。

    假设以这样的发那个是定义一个directive.

    app.directive("first", function(){
        return {
            restrict:"E",
            scope:{},//保持独立的scope
            controller: function($scope){
                $scope.abilities = [];
    
                this.addPower = function(){
                    $scope.abilities.push("power");
                }
    
                this.addVelocity = function(){
                    $scope.abilities.push("velocity");
                }
    
                this.addFly = function(){
                    $scope.abilities.push("fly");
                }
            },
            link:function(scope, element){
                element.bind("mouseenter", function(){
                    console.log(scope.abilities);
                })
            }
        }
    })


    scope字段保证了scope的独立性,并且是以元素形式声明。

    然后,分别针对以上first这个directive的3各方法自定义3个directive.

    app.directive("power", function(){
        return{
            require:"first",
            link: function(scope, element, attrs, first){
                first.addPower();
            }
        }
    })
    
    app.directive("velocity", function(){
        return{
            require:"first",
            link: function(scope, element, attrs, first){
                first.addVelocity();
            }
        }
    })
    
    
    app.directive("fly", function(){
        return{
            require:"first",
            link: function(scope, element, attrs, first){
                first.addFly();
            }
        }
    })

    以上,通过require获取到其它direcitive.

    在页面中按如下调用:

    <first power velocity fly>Superman</first>

  • 相关阅读:
    javascript判断触发事件event的鼠标按钮
    解决IE8 Session共享问题
    SignalR 实现web浏览器客户端与服务端的推送功能
    MFC ActiveX控件与ATL ActiveX控件的比较 .
    rpm relevent operation record
    通过rpm包安装、配置及卸载mysql的详细过程 Richard Shen 运维/架构 51CTO技术博客
    instal python relevent cmds
    ubuntu日志的设置
    关于电信、网通检测ADSL共享上网的技术手段
    Simple usage of Python's logging module
  • 原文地址:https://www.cnblogs.com/darrenji/p/5084352.html
Copyright © 2011-2022 走看看