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>

  • 相关阅读:
    .NET简谈互操作(七:数据封送之介绍)
    C# utf8编码时转换成shiftjis时出现乱码问题的处理
    .NET简谈特性(代码属性)
    著名Channel 9 主持人Robert Green 采访微软一站式示例代码库录像
    SharePoint 2007运行 Edit In DataSheet 时在IE 6下页面卡死的分析和处理方法
    截图工具
    Resharper上手指南
    .NET简谈互操作(三:基础知识之DllImport特性)
    .NET简谈互操作(五:基础知识之提升平台调用性能)
    深度训练(DotNet专场)
  • 原文地址:https://www.cnblogs.com/darrenji/p/5084352.html
Copyright © 2011-2022 走看看