AngularJS指令继承

AngularJS directive inheritance

本文关键字:继承 指令 AngularJS      更新时间:2023-09-26

我对Angular很陌生,我遇到了一个关于指令和继承的问题。假设有两个指令:

<my-pic    my-log="log pic"       my-warn="pic warn"    my-src="/some/url/pic.jpg"></my-pic>
<my-button my-log="log button"    my-warn="button warn" my-text="button text"></my-button>

JS代码

angular.module("app", [])
.directive("myPic",function(){
    return {
         restrict: "E"
        ,scope: {
             log: "@myLog"
            ,src: "@mySrc"
            ,warn:"@myWarn"
        }
        ,template: '<img src="{{src}}" title="{{log}} | {{warn}}"></img>'
        ,controller: function($scope, $log){
            $log.log($scope.log);
            $log.warn($scope.warn);
        }
    };
})
.directive("myButton",function(){
    return {
         restrict: "E"
        ,scope: {
             log:  "@myLog"
            ,text: "@myText"
            ,warn: "@myWarn"
        }
        ,template: '<button title="{{log}} | {{warn}}">{{text}}</button>'
        ,controller: function($scope, $log){
            $log.log($scope.log);
            $log.warn($scope.warn);
        }
    };
});

电笔http://codepen.io/anon/pen/VLMdRL

问题

问题是,是否可以创建第三个指令,从中可以派生MyPic和MyButton指令,并处理my log="…"和my warn="…"属性($log代码并将title属性添加到模板代码)?my log和my warn属性必须由同一指令处理,并且子指令仍然可以访问属性值。

谢谢你的帮助!

在这种情况下,您不需要继承。只需编写一个服务来处理常见的日志操作,并将其注入指令中。

好吧,我找到了一个可以接受的解决方案,但也许有更好的解决方案。我所做的是,我创建了第三个指令"myLogger",然后将其添加到"myButton"answers"myPic"指令的模板中。我还创建了一个函数,该函数被定义为常量,并将日志记录属性添加到指令的范围中。"myLogger"指令执行控制台日志记录并将"title"属性播发到HTML元素。

欢迎提出任何改进该解决方案的建议/想法。如果有人能提供更好的解决方案,我也将不胜感激。

HTML代码:

<my-pic    my-log="log pic"       my-warn="pic warn"    my-src="/some/url/pic.jpg"></my-pic>
<my-button my-log="log button"    my-warn="button warn" my-text="button text"></my-button>

Javascript代码:

angular.module("app", [])
.constant("addLogScope",function(opts){
    return angular.extend(opts || {},{
       myWarn: "@"
      ,myLog:  "@"
    });
})
.directive("myLogger",function(){
    return {
         restrict: "A"
        ,scope: true
        ,controller: function($scope, $log){
            console.log($scope.myLog);
            console.info($scope.myWarn);
        }
        ,link: function($scope, $element, $attrs){
            $element.prop("title",$scope.myLog + " | " + $scope.myWarn);
        }
    };
})
.directive("myPic",function(addLogScope){
    return {
         restrict: "E"
        ,scope: addLogScope({
            mySrc: "@"
        })
        ,transclude: true
        ,template: '<img src="{{mySrc}}" my-logger></img>'
        ,controller: function($scope){
        }
    };
})
.directive("myButton",function(addLogScope){
    return {
         restrict: "E"
        ,scope: addLogScope({
           myText: "@"
        })
        ,template: '<button my-logger>{{myText}}</button>'
        ,controller: function($scope){
        }
    };
});

代码笔:http://codepen.io/anon/pen/rVYgew