AngularJS指令继承

时间:2015-06-20 17:02:48

标签: javascript angularjs inheritance architecture

我对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属性必须由同一个指令处理,并且子指令仍然可以访问属性值。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

好的,我找到了一个可以忍受的解决方案,但也许有更好的解决方案可以做到这一点。我所做的是,我创建了第三个指令&#39; myLogger&#39;然后将其添加到&#39; myButton&#39;的模板中。和myPic&#39;指令。我还创建了一个定义为常量的函数,它将日志记录属性添加到指令的范围。 &#39; myLogger&#39;指令控制台记录和广告&#39;标题&#39;属性为HTML元素。

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

HTML code:

<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

相关问题